Biblioteca de vectores C ++ - función swap ()

Descripción

La función C ++ std::vector::swap() intercambia el contenido de dos vectores.

Declaración

A continuación se muestra la declaración de la función std :: vector :: swap () del encabezado std :: vector.

template <class T, class Alloc>
void swap (vector<T,Alloc>& v1, vector<T,Alloc>& v2);

Parámetros

  • v1 - Primer contenedor de vectores.

  • v2 - Segundo contenedor de vectores.

Valor devuelto

Ninguna.

Excepciones

Esta función nunca lanza una excepción.

Complejidad del tiempo

Lineal ie O (1)

Ejemplo

El siguiente ejemplo muestra el uso de la función std :: vector :: swap ().

#include <iostream>
#include <vector>

using namespace std;

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

   cout << "Contents of vector v1 before swap operation" << endl;
   for (int i = 0; i < v1.size(); ++i)
      cout << v1[i] << endl;

   cout << "Contents of vector v2 before swap operation" << endl;
   for (int i = 0; i < v2.size(); ++i)
      cout << v2[i] << endl;

   swap(v1, v2);
   cout << "Contents of vector v1 after swap operation" << endl;
   for (int i = 0; i < v1.size(); ++i)
      cout << v1[i] << endl;

   cout << "Contents of vector v2 after swap operation" << endl;
   for (int i = 0; i < v2.size(); ++i)
      cout << v2[i] << endl;

   return 0;
}

Compilemos y ejecutemos el programa anterior, esto producirá el siguiente resultado:

Contents of vector v1 before swap operation
1
2
3
4
5
Contents of vector v2 befor swap operation
10
20
30
Contents of vector v1 after swap operation
10
20
30
Contents of vector v2 after swap operation
1
2
3
4
5