Given myvector.start() and myvector.end() I want to create a read-only subset of myvector without copying the data.
Is this possible, and how?
#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() {
First I create the vector.
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
Then I want a subset. But I think this makes a copy.
// 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
How about this approach?
// 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
Or is the solution to declare all functions like f(const vector::iterator &start, const vector::iterator &en). The STL algorithms do this, right? (but generic)
Exit
std::cout << "Bye!" << std::endl;
return 0;
}
Just use iterators (const ones where appropriate).
If you’re really allergic to passing begin/end pairs around everywhere, consider using Boost.Range or something similar: it lets you bundle the
[start,end)pair into a single object.