菜鸟笔记
提升您的技术认知

vector赋值方法总结

大致有一下几种方法实现用于把一个vector赋值给另一个vector:

方法1:

vector<int > v1(v2);//声明

方法2:使用swap进行赋值:

vector<int > v1();v1.swap(v2);//将v2赋值给v1,此时v2变成了v1

方法3:使用函数assign进行赋值:

vector<int > 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 <iostream>
#include <vector>
using namespace std;

int main()
{
  
    //vector declaration
    vector<int> v1{
   10, 20, 30, 40, 50 };
    vector<int> 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<int >::iterator it;//声明迭代器
for(it = v2.begin();it!=v2.end();++it){
  //遍历v2,赋值给v1
     v1.push_back(it);
}