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

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


当前回答

将元素从一个向量复制到另一个向量很容易 在这个例子中,为了便于理解,我使用了一对向量 `

vector<pair<int, int> > v(n);

//we want half of elements in vector a and another half in vector b
vector<pair<lli, lli> > a(v.begin(),v.begin()+n/2);
vector<pair<lli, lli> > b(v.begin()+n/2, v.end());


//if v = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
//then a = [(1, 2), (2, 3)]
//and b = [(3, 4), (4, 5), (5, 6)]

//if v = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
//then a = [(1, 2), (2, 3), (3, 4)]
//and b = [(4, 5), (5, 6), (6, 7)]

' 正如你所看到的,你可以很容易地将元素从一个向量复制到另一个向量,例如,如果你想将元素从索引10复制到索引16,那么我们将使用

vector<pair<int, int> > a(v.begin()+10, v.begin+16);

如果你想让元素从索引10到末尾的某个索引,那么在这种情况下

vector<pair<int, int> > a(v.begin()+10, v.end()-5);

希望这有助于,只要记住在最后的情况下v.end()-5 > v.begin()+10

其他回答

Vector::assign可能是另一个解决方案

// note: size1 < src.size() && size2 < src.size()
std::vector<int> sub1(size1), sub2(size2);
sub1.assign(src.begin(), src.begin() + size1);
sub2.assign(src.begin(), src.begin() + size2);

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

还有另一个选择: 例如,当在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<int> vect1{1, 2, 3, 4};
 vector<int> vect2;

方法1。使用拷贝功能。copy(first_iterator_index, last_iterator_index, back_inserter()):-该函数有3个参数,首先,旧vector的第一个迭代器。其次,old vector的最后一个迭代器和第三个迭代器是back_inserter函数,用于从back插入值。

    // Copying vector by copy function
    copy(vect1.begin(), vect1.end(), back_inserter(vect2));

方法2。通过使用赋值函数。分配(first_iterator_o last_iterator_o)。该方法将相同的值赋给新向量和旧向量。它有两个参数,第一个迭代器指向旧向量,最后一个迭代器指向旧向量。

    //Copying vector by assign function
    vect2.assign(vect1.begin(), vect1.end());

这个讨论已经很老了,但是最简单的一个还没有提到,就是列表初始化:

 vector<int> subvector = {big_vector.begin() + 3, big_vector.end() - 2}; 

它要求c++11或以上。

使用示例:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){

    vector<int> big_vector = {5,12,4,6,7,8,9,9,31,1,1,5,76,78,8};
    vector<int> subvector = {big_vector.begin() + 3, big_vector.end() - 2};

    cout << "Big vector: ";
    for_each(big_vector.begin(), big_vector.end(),[](int number){cout << number << ";";});
    cout << endl << "Subvector: ";
    for_each(subvector.begin(), subvector.end(),[](int number){cout << number << ";";});
    cout << endl;
}

结果:

Big vector: 5;12;4;6;7;8;9;9;31;1;1;5;76;78;8;
Subvector: 6;7;8;9;9;31;1;1;5;76;