Namespaces
Variants

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

From cppreference.net

void swap ( stack & other ) noexcept ( /* см. ниже */ ) ;
(начиная с C++11)
Exchanges the contents of the container adaptor with those of other . Effectively calls
using std::swap;
swap(c, other.c);

Содержание

Параметры

other - адаптер контейнера для обмена содержимым с

Возвращаемое значение

(нет)

Исключения

noexcept спецификация:
noexcept ( noexcept ( swap ( c, other. c ) ) )

В приведенном выше выражении идентификатор swap ищется таким же образом, как и в трейте C++17 std::is_nothrow_swappable .

(начиная с C++11)
(до C++17)
noexcept спецификация:
noexcept ( std:: is_nothrow_swappable_v < Container > )
(начиная с C++17)

Сложность

Так же, как у базового контейнера (обычно константа).

Примечания

Некоторые реализации (например, libc++) предоставляют swap функцию-член как расширение для режимов до C++11.

Пример

#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);
}

Вывод:

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

Отчеты о дефектах

Следующие отчеты об изменениях поведения, влияющие на дефекты, были применены ретроактивно к ранее опубликованным стандартам C++.

DR Применяется к Поведение в опубликованной версии Корректное поведение
LWG 2456 C++11 спецификация noexcept некорректна исправлено для работы

Смотрите также

специализирует алгоритм std::swap
(шаблон функции)