给定 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;
}