名前空間
変種
操作

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

From cppreference.com
< cpp‎ | コンテナ‎ | stack
 
 
 
 
void swap( stack& other ) noexcept(/* 下記参照 */);
(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++) では、C++11 より前のモードへの拡張として swap メンバ関数が提供されています。

[編集]

#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 アルゴリズムを特殊化する
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)