Biblioteca C ++ Deque - função swap ()

Descrição

A função C ++ std::deque::swap()troca o conteúdo do primeiro deque por outro. Esta função altera o tamanho do deque, se necessário.

Declaração

A seguir está a declaração para o formulário de função std :: deque :: swap () std :: deque header.

C ++ 98

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

Parâmetros

  • first - Primeiro objeto deque.

  • second - Segundo objeto deque.

Valor de retorno

Nenhum.

Exceções

Esta função de membro nunca lança exceção.

Complexidade de tempo

Linear, ou seja, O (n)

Exemplo

O exemplo a seguir mostra o uso da função 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;

   swap(d1, 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;
}

Vamos compilar e executar o programa acima, isso produzirá o seguinte resultado -

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