大致有一下几种方法实现用于把一个vector赋值给另一个vector:
方法1:
vector v1(v2);//声明
方法2:使用swap进行赋值:
vector v1();v1.swap(v2);//将v2赋值给v1,此时v2变成了v1
方法3:使用函数assign进行赋值:
vector v1;//声明v1
v1.assign(v2.begin(), v2.end());//将v2赋值给v1
例程:c program to demonstrate example of vector::swap() function
//c stl program to demonstrate example of
//vector::erase() function
#include
#include
using namespace std;
int main()
{
//vector declaration
vector v1{
10, 20, 30, 40, 50 };
vector v2{
100, 200, 300 };
//printing the sizes and values of the vectors
cout << "before swap() call..." << endl;
cout << "size of v1: " << v1.size() << endl;
cout << "size of v2: " << v2.size() << endl;
cout << "v1: ";
for (int x : v1)
cout << x << " ";
cout << endl;
cout << "v2: ";
for (int x : v2)
cout << x << " ";
cout << endl;
//swapping the content of the vectors
v1.swap(v2);
//printing the sizes and values of the vectors
cout << "after swap() call..." << endl;
cout << "size of v1: " << v1.size() << endl;
cout << "size of v2: " << v2.size() << endl;
cout << "v1: ";
for (int x : v1)
cout << x << " ";
cout << endl;
cout << "v2: ";
for (int x : v2)
cout << x << " ";
cout << endl;
return 0;
}
output:
before swap() call...
size of v1: 5
size of v2: 3
v1: 10 20 30 40 50
v2: 100 200 300
after swap() call...
size of v1: 3
size of v2: 5
v1: 100 200 300
v2: 10 20 30 40 50
方法4:使用循环语句赋值,效率较差
vector::iterator it;//声明迭代器
for(it = v2.begin();it!=v2.end(); it){
//遍历v2,赋值给v1
v1.push_back(it);
}