Namensräume
Varianten
Aktionen

std::swap(std::stack)

Von cppreference.com
< cpp‎ | container‎ | stack
 
 
 
 
Definiert in Header <stack>
template< class T, class Container >

void swap( std::stack<T, Container>& lhs,

           std::stack<T, Container>& rhs );
(seit C++11)
(bis C++17)
template< class T, class Container >

void swap( std::stack<T, Container>& lhs,
           std::stack<T, Container>& rhs )

               noexcept(/* siehe unten */);
(seit C++17)
Spezialisiert den std::swap Algorithmus für std::stack. Vertauscht die Inhalte von lhs und rhs. Ruft lhs.swap(rhs) auf.

Diese Überladung nimmt nur an der Auflösungsüberladung teil, wenn std::is_swappable_v<Container> true ist.

(seit C++17)

Inhalt

[bearbeiten] Parameter

lhs, rhs - Container, deren Inhalte getauscht werden sollen

[bearbeiten] Rückgabewert

(keine)

[bearbeiten] Komplexität

Gleichbedeutend mit dem Vertauschen der zugrunde liegenden Container.

Ausnahmen

noexcept-Spezifikation:  
noexcept(noexcept(lhs.swap(rhs)))
(seit C++17)

Anmerkungen

Obwohl die Überladungen von std::swap für Container-Adapter in C++11 eingeführt wurden, können Container-Adapter bereits in C++98 mit std::swap vertauscht werden. Solche Aufrufe von std::swap haben normalerweise eine lineare Zeitkomplexität, aber eine bessere Komplexität kann bereitgestellt werden.

[bearbeiten] Beispiel

#include <algorithm>
#include <iostream>
#include <stack>
 
int main()
{
    std::stack<int> alice;
    std::stack<int> bob;
 
    auto print = [](const auto& title, const auto& cont)
    {
        std::cout << title << " size=" << cont.size();
        std::cout << " top=" << cont.top() << '\n';
    };
 
    for (int i = 1; i < 4; ++i)
        alice.push(i);
    for (int i = 7; i < 11; ++i)
        bob.push(i);
 
    // Print state before swap
    print("Alice:", alice);
    print("Bobby:", bob);
 
    std::cout << "-- SWAP\n";
    std::swap(alice, bob);
 
    // Print state after swap
    print("Alice:", alice);
    print("Bobby:", bob);
}

Ausgabe

Alice: size=3 top=3
Bobby: size=4 top=10
-- SWAP
Alice: size=4 top=10
Bobby: size=3 top=3

[bearbeiten] Siehe auch

(C++11)
tauscht die Inhalte
(public member function) [edit]