Namespaces
Variants

std::stack<T,Container>:: swap

From cppreference.net

void swap ( stack & other ) noexcept ( /* siehe unten */ ) ;
(seit C++11)
Exchanges the contents of the container adaptor with those of other . Effectively calls
using std::swap;
swap(c, other.c);

Inhaltsverzeichnis

Parameter

other - Container-Adaptor, mit dem die Inhalte ausgetauscht werden sollen

Rückgabewert

(keine)

Ausnahmen

noexcept Spezifikation:
noexcept ( noexcept ( swap ( c, other. c ) ) )

Im obigen Ausdruck wird der Bezeichner swap auf dieselbe Weise gesucht, wie es vom C++17-Merkmal std::is_nothrow_swappable verwendet wird.

(seit C++11)
(bis C++17)
noexcept Spezifikation:
noexcept ( std:: is_nothrow_swappable_v < Container > )
(seit C++17)

Komplexität

Gleich wie zugrunde liegender Container (typischerweise konstant).

Hinweise

Einige Implementierungen (z.B. libc++) bieten die swap Member-Funktion als Erweiterung für Pre-C++11-Modi an.

Beispiel

#include <iostream>
#include <concepts>
#include <stack>
#include <string>
#include <string_view>
#include <vector>
template<typename Adaptor>
requires (std::ranges::input_range<typename Adaptor::container_type>)
void print(std::string_view name, const Adaptor& adaptor)
{
    struct Printer : Adaptor // to use protected Adaptor::Container c;
    {
        void print(std::string_view name) const
        {
            std::cout << name << " [" << std::size(this->c) << "]: ";
            for (auto const& elem : this->c)
                std::cout << elem << ' ';
            std::cout << '\n';
        }
    };
    static_cast<Printer const&>(adaptor).print(name);
}
int main()
{
    std::vector<std::string> v1{"1","2","3","4"},
                             v2{"Ɐ","B","Ɔ","D","Ǝ"};
    std::stack s1(std::move(v1));
    std::stack s2(std::move(v2));
    print("s1", s1);
    print("s2", s2);
    s1.swap(s2);
    print("s1", s1);
    print("s2", s2);
}

Ausgabe:

s1 [4]: 4 3 2 1
s2 [5]: Ǝ D Ɔ B Ɐ
s1 [5]: Ǝ D Ɔ B Ɐ
s2 [4]: 4 3 2 1

Fehlerberichte

Die folgenden verhaltensändernden Fehlerberichte wurden rückwirkend auf zuvor veröffentlichte C++-Standards angewendet.

DR Angewendet auf Verhalten wie veröffentlicht Korrektes Verhalten
LWG 2456 C++11 die noexcept Spezifikation ist fehlerhaft funktionsfähig gemacht

Siehe auch

spezialisiert den std::swap Algorithmus
(Funktions-Template)