Namespaces
Variants

std::vector<bool,Allocator>:: swap

From cppreference.net
ヘッダーで定義 <vector>
static void swap ( reference x, reference y ) ;
(C++20以降 constexpr)

x y の内容を、以下のように交換します bool b = x ; x = y ; y = b ;

目次

パラメータ

x - std::vector < bool > :: reference y と交換する値
y - std::vector < bool > :: reference x と交換する値

戻り値

(なし)

計算量

定数。

#include <iostream>
#include <vector>
void println(std::string_view fmt, std::vector<bool> const& vb = {})
{
    for (std::cout << fmt; bool const e : vb)
        std::cout << e << ' ';
    std::cout << '\n';
}
int main()
{
    println("swap elements of the same vector:");
    std::vector<bool> x{1, 0};
    println("before swap, x: ", x);
    x.swap(x[0], x[1]); // same as std::vector<bool>::swap(x[0], x[1]);
    println("after swap,  x: ", x);
    println("swap elements of two different vectors:");
    std::vector<bool> y{0, 0, 1};
    println("before swap, x: ", x);
    println("before swap, y: ", y);
    y.swap(x[0], y[2]); // same as std::vector<bool>::swap(x[0], y[2]);
    println("after swap,  x: ", x);
    println("after swap,  y: ", y);
}

出力:

swap elements of the same vector:
before swap, x: 1 0 
after swap,  x: 0 1 
swap elements of two different vectors:
before swap, x: 0 1 
before swap, y: 0 0 1 
after swap,  x: 1 1 
after swap,  y: 0 0 0

欠陥報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 814 C++98 このメンバー関数の説明が欠落していた 追加された

関連項目

単一の bool への参照を表すプロキシクラス
(クラス)
内容を交換する
( std::vector<T,Allocator> の公開メンバ関数)
std::swap アルゴリズムを特殊化する
(関数テンプレート)