cpp / latest / container / stack / swap.html /

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

void swap( stack& other ) noexcept(/* see below */);
(since C++11)

Exchanges the contents of the container adaptor with those of other. Effectively calls using std::swap; swap(c, other.c);

Parameters

other - container adaptor to exchange the contents with

Return value

(none).

Exceptions

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

In the expression above, the identifier swap is looked up in the same manner as the one used by the C++17 std::is_nothrow_swappable trait.

(since C++11)
(until C++17)
noexcept specification:
noexcept(std::is_nothrow_swappable_v<Container>)
(since C++17)

Complexity

Same as underlying container (typically constant).

Notes

Some implementations (e.g. libc++) provide the swap member function as an extension to pre-C++11 modes.

Example

#include <iostream>
#include <stack>
#include <string>
#include <vector>
 
template <typename Stack>
void print(Stack stack /* pass by value */, int id)
{
    std::cout << "s" << id << " [" << stack.size() << "]: ";
    for (; !stack.empty(); stack.pop())
        std::cout << stack.top() << ' ';
    std::cout << (id > 1 ? "\n\n" : "\n");
}
 
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, 1);
    print(s2, 2);
 
    s1.swap(s2);
 
    print(s1, 1);
    print(s2, 2);
}

Output:

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

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 2456 C++11 the noexcept specification is ill-formed made to work

See also

(C++11)
specializes the std::swap algorithm
(function template)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/container/stack/swap