C++ Vector Library - swap() Function



Description

The C++ function std::vector::swap() exchanges the content of vector with contents of vector x.

Declaration

Following is the declaration for std::vector::swap() function form std::vector header.

C++98

void swap (vector& x);

Parameters

x − Another vector object of same type.

Return value

None

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::vector::swap() function.

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v1;
   vector<int> v2 = {1, 2, 3, 4, 5};

   v1.swap(v2);

   cout << "Vector v1 contains" << endl;
   for (int i = 0; i < v1.size(); ++i)
      cout << v1[i] << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Vector v1 contains
1
2
3
4
5
vector.htm
Advertisements