myvector.start()とmyvector.end()が与えられた場合、データをコピーせずにmyvectorの読み取り専用サブセットを作成したいと思います。
これは可能ですか、そしてどのように?
#include <iostream>
#include <vector>
using namespace std;
template <class T> void print_vector(const vector<T> &v) {
for(size_t i = 0; i < v.size(); ++i) std::cout << v[i] << " ";
std::cout << std::endl;
}
int main() {
まず、ベクトルを作成します。
vector<double> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print_vector(data); // 1 2 3 4 5 6 7 8 9 10
次に、サブセットが必要です。しかし、これはコピーになると思います。
// Does this make a copy or not? I don't want to make a copy.
const vector<double> subset1(data.begin() + 3, data.end() - 3);
print_vector(subset1); // 4 5 6 7
このアプローチはどうですか?
// Another approach. Questions:
// - Would something like this be a good alternative if I really don't want a copy?
// - How would the performance of this be compared to a normal STL container?
// - Is there an existing implementation of a container that does something like this, maybe a boost class?
class SubsetType {
public:
SubsetType(const vector<double>::iterator &start, const vector<double>::iterator &end) { begin_ = start; end_ = end; }
vector<double>::iterator begin() { return begin_; }
vector<double>::iterator end() { return end_; }
double operator[](vector<double>::size_type i) { return *(begin_ + i); }
vector<double>::size_type size() { return end_ - begin_; }
private:
vector<double>::iterator begin_, end_;
};
SubsetType subset2(data.begin() + 3, data.end() - 3);
for(size_t i = 0; i < subset2.size(); ++i) std::cout << subset2[i] << " ";
std::cout << std::endl; // 4 5 6 7
または、f(const vector :: iterator&start、const vector :: iterator&en)のようなすべての関数を宣言するソリューションです。STLアルゴリズムはこれを行いますよね?(ただし一般的)
出口
std::cout << "Bye!" << std::endl;
return 0;
}