vector::operator=


public member function
vector<T,Allocator>& operator= (const vector<T,Allocator>& x);

Copy vector content

Assigns a copy of vector x as the new content for the vector object.

The elements contained in the vector object before the call are dropped, and replaced by copies of those in vector x, if any.

After a call to this member function, both the vector object and vector x will have the same size and compare equal to each other.

Parameters

x
A vector object containing elements of the same type.


Return value

*this

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// vector assignment
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> first (3,0);
  vector<int> second (5,0);

  second=first;
  first=vector<int>();

  cout << "Size of first: " << int (first.size()) << endl;
  cout << "Size of second: " << int (second.size()) << endl;
  return 0;
}

Both vectors of int elements are initialized to sequences of zeros of different sizes. Then, second is assigned to first, so both are now equal and with a size of 3. And then, first is assigned to a newly constructed empty object, so its size is finally 0. Output:
Size of first: 0
Size of second: 3


Complexity

Linear on sizes (destruction, copy construction).

See also