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

La description

La fonction C ++ std::list::swap()échange le contenu de la première liste avec une autre. Cette fonction change la taille de la liste si nécessaire.

Déclaration

Voici la déclaration de la fonction std :: list :: swap () sous forme d'en-tête std :: list.

C ++ 98

template <class T, class Alloc>
void swap (list<T,Alloc>& first, list<T,Alloc>& second);

Paramètres

  • first - Premier objet de liste.

  • second - Deuxième objet de liste.

Valeur de retour

Aucun.

Des exceptions

Cette fonction ne lève jamais d'exception.

Complexité temporelle

Linéaire ie O (n)

Exemple

L'exemple suivant montre l'utilisation de la fonction std :: list :: swap ().

#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l1 = {1, 2, 3};
   list<int> l2 = {10, 20, 30, 40, 50};

   cout << "List l1 contains following elements before swap operation" << endl;
   for (auto it = l1.begin(); it != l1.end(); ++it)
      cout << *it << endl;

   cout << "List l2 contains following elements before swap operation" << endl;
   for (auto it = l2.begin(); it != l2.end(); ++it)
      cout << *it << endl;

   swap(l1, l2);

   cout << "List l1 contains following elements after swap operation" << endl;
   for (auto it = l1.begin(); it != l1.end(); ++it)
      cout << *it << endl;

   cout << "List l2 contains following elements after swap operation" << endl;
   for (auto it = l2.begin(); it != l2.end(); ++it)
      cout << *it << endl;

   return 0;
}

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

List l1 contains following elements before swap operation
1
2
3
List l2 contains following elements before swap operation
10
20
30
40
50
List l1 contains following elements after swap operation
10
20
30
40
50
List l2 contains following elements after swap operation
1
2
3