名前空間
変種
操作

std::array<T,N>::swap

From cppreference.com
< cpp‎ | container‎ | array
 
 
 
 
void swap( array& other ) noexcept(/* 以下参照 */);
(C++11以降)
(C++20 以降 constexpr)

コンテナの内容をotherの内容と交換します。イテレータや参照が他のコンテナに関連付けられることはありません。

目次

[編集] パラメータ

その他 - 内容を交換するコンテナ

[編集] 戻り値

(なし)

[編集] 例外

noexcept 指定:  
noexcept(noexcept(swap(std::declval<T&>(), std::declval<T&>())))

上記の式において、識別子swapは、C++17のstd::is_nothrow_swappableトレイトが使用するものと同じ方法で検索されます。

(C++17まで)
noexcept 指定:  
(C++17以降)
サイズゼロの配列の場合、
noexcept 指定:  
noexcept
  

[編集] 計算量

コンテナのサイズに対して線形。

[編集]

#include <array>
#include <iostream>
 
template<class Os, class V> Os& operator<<(Os& os, const V& v)
{
    os << '{';
    for (auto i : v)
        os << ' ' << i;
    return os << " } ";
}
 
int main()
{
    std::array<int, 3> a1{1, 2, 3}, a2{4, 5, 6};
 
    auto it1 = a1.begin();
    auto it2 = a2.begin();
    int& ref1 = a1[1];
    int& ref2 = a2[1];
 
    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
    a1.swap(a2);
    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
 
    // Note that after swap iterators and references stay associated with their original
    // array, e.g. `it1` still points to element a1[0], `ref1` still refers to a1[1].
}

出力

{ 1 2 3 } { 4 5 6 } 1 4 2 5
{ 4 5 6 } { 1 2 3 } 4 1 5 2

[編集] 不具合報告

以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。

DR 適用対象 公開された動作 正しい動作
LWG 2456 C++11 noexcept指定が不正形式 動作するように修正

[編集] 関連項目

std::swap アルゴリズムを特殊化する
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)