Bibliothèque de vecteurs C ++ - fonction swap ()

La description

La fonction C ++ std::vector::swap() échange le contenu de deux vecteurs.

Déclaration

Voici la déclaration de l'en-tête std :: vector :: swap () de la fonction std :: vector :: swap ().

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

Paramètres

  • v1 - Premier conteneur de vecteur.

  • v2 - Deuxième conteneur de vecteur.

Valeur de retour

Aucun.

Des exceptions

Cette fonction ne lève jamais d'exception.

Complexité temporelle

Linéaire ie O (1)

Exemple

L'exemple suivant montre l'utilisation de la fonction 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;
}

Compilons et exécutons le programme ci-dessus, cela produira le résultat suivant -

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