std::vector<bool,Allocator>::swap
From cppreference.com
| Defined in header <vector>
|
||
static void swap( reference x, reference y );
|
(noexcept since C++11) (constexpr since C++20) (deprecated in C++26) |
|
Swaps the bits referenced by x and y as if by
bool b = x;
x = y;
y = b;
.
Parameters
| x,y | - | values to be swapped |
Complexity
Constant.
Example
Run this code
#include <print>
#include <vector>
int main()
{
std::println("Swap elements of the same vector:");
std::vector<bool> x{1, 0};
std::println("Before swap, x: {}", x);
x.swap(x[0], x[1]); // same as std::vector<bool>::swap(x[0], x[1]);
std::println("After swap, x: {}", x);
std::println("Swap elements of two different vectors:");
std::vector<bool> y{0, 0, 1};
std::println("Before swap, x: {}", x);
std::println("Before swap, y: {}", y);
y.swap(x[0], y[2]); // same as std::vector<bool>::swap(x[0], y[2]);
std::println("After swap, x: {}", x);
std::println("After swap, y: {}", y);
}
Output:
Swap elements of the same vector:
Before swap, x: [true, false]
After swap, x: [false, true]
Swap elements of two different vectors:
Before swap, x: [false, true]
Before swap, y: [false, false, true]
After swap, x: [true, true]
After swap, y: [false, false, false]
Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 814 | C++98 | the description of this member function was missing | added |
| LWG 3638 (P3612R1) |
C++98 | the swap function was a memberof std::vector<bool>
|
provided non-member versions and deprecated the member version |
See also
proxy class representing a reference to a single bool (class) | |
| swaps the contents (public member function of std::vector<T,Allocator>)
| |
| overloads the std::swap algorithm (function template) |