首先看下在整个container上面的复制.

c1=c2

可以等同于

c1.erase(c1.begin(),c1.end()) //delete all elems in c1

c1.insert(c1.begin(),c2.begin(),c2.end);

 

在赋值后,c1和c2完全相等,即使他们曾经的size不相等,赋值后也相等了。

=和assign操作会是左边的容器的迭代器失效。然而,swap不会使迭代器失效。after swap,iteratros continue to refer to the 

same elements,although those elements are now in a different container.

 

=赋值操作符可以使用仅当elememtn type元素类型相同时,如果我们want to assign elements of a differenct but compatible element type and/or from a different container type,,我们必须使用assign函数。例如:我们可以使用assign 函数 to 

assign a range of char* values from a vector into list of string.

vector<int> v1(3,1);
    vector<int> v2(5,2);
     v1=v2; ;//v1也v2完全相等

assign原型:

range (1)
template <class InputIterator>
  void assign (InputIterator first, InputIterator last);
fill (2)
void assign (size_type n, const value_type& val);

vector<int> v1(3,1);
    v1.assign(10,5);//v1变成了10个5
         vector<int> v1(3,1);
     
     vector<int> v2(5,2);
     
     v1.assign(v2.begin(),v2.begin()+1);把v2的首元素赋值给v1,v2就只有一个元素了。

可以看到,assign后原来的元素都不存在了。assign操作首先会删除所有的元素,然后插入赋值的元素。

swap函数交换2个操作数的值。the type of contianer must match:

the operands must be the same kind of container.,and they must hold values of the same type.

after the call to swap,the elements that had been in the right-hand operand are in the left。

vector<int> v3(5,1);
    vector<int> v4(3,2);
    v3.swap(v4); //v3变成了v4,v4变成了v3