假设我有一个大小为n的std::vector(让我们称之为myVec),构造一个由元素X到Y的副本组成的新向量,其中0 <= X <= Y <= N-1,最简单的方法是什么?例如,大小为150000的向量中的myVec[100000]到myVec[100999]。

如果这不能有效地用一个向量,是否有另一种STL数据类型,我应该使用代替?


当前回答

现在,我们使用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.

其他回答

当M是子向量的大小时,可以使用性能为O(M)的STL复制。

如果这两个都不打算修改(不添加/删除项-只要注意线程问题,修改现有项就可以),您可以简单地传递data.begin() + 100000和data.begin() + 101000,并假装它们是一个更小的向量的begin()和end()。

或者,因为矢量存储保证是连续的,你可以简单地传递一个1000项数组:

T *arrayOfT = &data[0] + 100000;
size_t arrayOfTLength = 1000;

这两种技术都需要固定的时间,但要求数据长度不增加,从而触发重新分配。

还有另一个选择: 例如,当在thrust::device_vector和thrust::host_vector之间移动时很有用,在那里您不能使用构造函数。

std::vector<T> newVector;
newVector.reserve(1000);
std::copy_n(&vec[100000], 1000, std::back_inserter(newVector));

复杂度也应该是O(N)

您可以将此与顶部答案代码结合起来

vector<T>::const_iterator first = myVec.begin() + 100000;
vector<T>::const_iterator last = myVec.begin() + 101000;
std::copy(first, last, std::back_inserter(newVector));

std::vector<T>(input_iterator, input_iterator),在你的情况下,foo = std::vector<T>(myVec。begin () + 100000, myVec。Begin() + 150000);,参见这里的示例

投射一个不是线性时间的集合的唯一方法是惰性地这样做,其中产生的“vector”实际上是委托给原始集合的子类型。例如,Scala的List#subseq方法在常数时间内创建一个子序列。但是,只有当收集是不可变的并且底层语言支持垃圾收集时,这才有效。