Namespaces
Variants

std:: swap (std::stack)

From cppreference.net

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)
(constexpr seit C++26)
Specializes the std::swap algorithm for std::stack . Swaps the contents of lhs and rhs . Calls lhs. swap ( rhs ) .

Diese Überladung nimmt nur dann an der Überladungsauflösung teil, wenn std:: is_swappable_v < Container > true ist.

(since C++17)

Inhaltsverzeichnis

Parameter

lhs, rhs - Container, deren Inhalte ausgetauscht werden sollen

Komplexität

Gleichbedeutend mit dem Austausch der zugrundeliegenden Container.

Ausnahmen

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

Hinweise

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

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);
    // Zustand vor Swap ausgeben
    print("Alice:", alice);
    print("Bobby:", bob);
    std::cout << "-- SWAP\n";
    std::swap(alice, bob);
    // Zustand nach Swap ausgeben
    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

Siehe auch

(C++11)
tauscht die Inhalte aus
(öffentliche Elementfunktion)