假设我有一个大小为n的std::vector(让我们称之为myVec),构造一个由元素X到Y的副本组成的新向量,其中0 <= X <= Y <= N-1,最简单的方法是什么?例如,大小为150000的向量中的myVec[100000]到myVec[100999]。
如果这不能有效地用一个向量,是否有另一种STL数据类型,我应该使用代替?
假设我有一个大小为n的std::vector(让我们称之为myVec),构造一个由元素X到Y的副本组成的新向量,其中0 <= X <= Y <= N-1,最简单的方法是什么?例如,大小为150000的向量中的myVec[100000]到myVec[100999]。
如果这不能有效地用一个向量,是否有另一种STL数据类型,我应该使用代替?
当前回答
你可以使用insert
vector<type> myVec { n_elements };
vector<type> newVec;
newVec.insert(newVec.begin(), myVec.begin() + X, myVec.begin() + Y);
其他回答
当M是子向量的大小时,可以使用性能为O(M)的STL复制。
std::vector<T>(input_iterator, input_iterator),在你的情况下,foo = std::vector<T>(myVec。begin () + 100000, myVec。Begin() + 150000);,参见这里的示例
只要使用向量构造函数。
std::vector<int> data();
// Load Z elements into data so that Z > Y > X
std::vector<int> sub(&data[100000],&data[101000]);
现在,我们使用span !所以你可以这样写:
#include <gsl/span>
...
auto start_pos = 100000;
auto length = 1000;
auto span_of_myvec = gsl::make_span(myvec);
auto my_subspan = span_of_myvec.subspan(start_pos, length);
以获得与myvec相同类型的1000个元素的跨度。或者更简洁的形式:
auto my_subspan = gsl::make_span(myvec).subspan(1000000, 1000);
(但我不太喜欢这个,因为每个数字参数的含义并不完全清楚;如果长度和start_pos是同一个数量级,情况会变得更糟。)
不管怎样,记住这不是一个副本,它只是向量中数据的一个视图,所以要小心。如果你想要一个实际的副本,你可以这样做:
std::vector<T> new_vec(my_subspan.cbegin(), my_subspan.cend());
注:
gsl stands for Guidelines Support Library. For more information about gsl, see: http://www.modernescpp.com/index.php/c-core-guideline-the-guidelines-support-library. There are several gsl implementations . For example: https://github.com/martinmoene/gsl-lite C++20 provides an implementation of span. You would use std::span and #include <span> rather than #include <gsl/span>. For more information about spans, see: What is a "span" and when should I use one? std::vector has a gazillion constructors, it's super-easy to fall into one you didn't intend to use, so be careful.
我打赌第一个编码器现在已经完成了。 对于简单的数据类型,不需要复制,只需恢复到良好的旧C代码方法。
std::vector <int> myVec;
int *p;
// Add some data here and set start, then
p=myVec.data()+start;
然后将指针p和len传递给任何需要子向量的对象。
Notelen一定是!!len < myVec.size()-start