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

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


当前回答

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

其他回答

还有另一个选择: 例如,当在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));

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

vector<T>::const_iterator first = myVec.begin() + 100000;
vector<T>::const_iterator last = myVec.begin() + 101000;
vector<T> newVec(first, last);

这是一个O(N)运算来构造新的向量,但是没有更好的方法了。

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

你没有提到什么类型std::vector<…> myVec是,但如果它是一个简单的类型或结构/类,不包括指针,你想要最好的效率,那么你可以做一个直接的内存复制(我认为这将比其他答案提供的更快)。下面是std::vector<type> myVec的一般示例,这里的类型是int:

typedef int type; //choose your custom type/struct/class
int iFirst = 100000; //first index to copy
int iLast = 101000; //last index + 1
int iLen = iLast - iFirst;
std::vector<type> newVec;
newVec.resize(iLen); //pre-allocate the space needed to write the data directly
memcpy(&newVec[0], &myVec[iFirst], iLen*sizeof(type)); //write directly to destination buffer from source buffer