Bibliothèque C ++ Forward_list - fonction swap ()

La description

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

Déclaration

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

C ++ 11

void swap (forward_list& other);

Paramètres

other - Un autre objet forward_list du même type.

Valeur de retour

Aucun

Des exceptions

Cette fonction membre ne lève jamais d'exception.

Complexité temporelle

Constante ie O (1)

Exemple

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

#include <iostream>
#include <forward_list>

using namespace std;

int main(void) {

   forward_list<int> fl1 = {1, 2, 3, 4, 5};;
   forward_list<int> fl2 = {10, 20, 30};

   cout << "List fl1 contents before swap operation" << endl;

   for (auto it = fl1.begin(); it != fl1.end(); ++it)
      cout << *it << endl;

   cout << "List fl2 contents before swap operation" << endl;

   for (auto it = fl2.begin(); it != fl2.end(); ++it)
      cout << *it << endl;

   fl1.swap(fl2);

   cout << endl;

   cout << "List fl1 contents after swap operation" << endl;

   for (auto it = fl1.begin(); it != fl1.end(); ++it)
      cout << *it << endl;

   cout << "List fl2 contents after swap operation" << endl;

   for (auto it = fl2.begin(); it != fl2.end(); ++it)
      cout << *it << endl;
   return 0;
}

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

List fl1 contents before swap operation
1
2
3
4
5
List fl2 contents before swap operation
10
20
30

List fl1 contents after swap operation
10
20
30
List fl2 contents after swap operation
1
2
3
4
5