命名空间
变体
操作

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

来自 cppreference.cn
 
 
 
 
定义于头文件 <vector>
static void swap( reference x, reference y );
(constexpr 自 C++20 起)

交换 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 算法
(函数模板) [编辑]