名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ |
void swap( stack& other ) noexcept(/* see below */);
(C++11 起)
交換容器介面卡與 other 的內容。實際呼叫
using std::swap;
swap(c, other.c);

目錄

[編輯] 引數

其他 - 用於交換內容的容器介面卡

[編輯] 返回值

(無)

[編輯] 異常

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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2456 C++11 noexcept 規範格式錯誤 已修復

[編輯] 參閱

特化 std::swap 演算法
(函式模板) [編輯]