C ++ Deque Library - Funzione swap ()

Descrizione

La funzione C ++ std::deque::swap()scambia il contenuto del primo deque con un altro. Questa funzione modifica la dimensione della deque se necessario.

Dichiarazione

Di seguito è riportata la dichiarazione per la funzione std :: deque :: swap () nel modulo std :: deque header.

C ++ 98

void swap (deque& x);

C ++ 11

void swap (deque& x);

Parametri

x - Un altro oggetto deque dello stesso tipo.

Valore di ritorno

Nessuna.

Eccezioni

Questa funzione membro non genera mai eccezioni.

Complessità temporale

Costante cioè O (1)

Esempio

L'esempio seguente mostra l'utilizzo della funzione std :: deque :: swap ().

#include <iostream>
#include <deque>

using namespace std;

int main(void) {

   deque<int> d1 = {1, 2, 3, 4, 5};
   deque<int> d2 = {50, 60, 70};

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

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

   cout << endl;

   d1.swap(d2);

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

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

   return 0;
}

Compiliamo ed eseguiamo il programma sopra, questo produrrà il seguente risultato:

Content of d1 before swap operation
1
2
3
4
5
Content of d2 before swap operation
50
60
70

Content of d1 after swap operation
50
60
70
Content of d2 after swap operation
1
2
3
4
5