std::inplace_vector<T,N>::swap
來自 cppreference.com
< cpp | 容器 | inplace_vector
constexpr void swap( inplace_vector& other ) noexcept(/* see below */); |
(C++26 起) | |
將容器內容與 other 的內容交換。不會導致迭代器和引用與另一個容器關聯。
目錄 |
[編輯] 引數
其他 | - | 用於交換內容的容器 |
[編輯] 返回值
(無)
[編輯] 異常
noexcept 規範:
noexcept(N == 0 ||
(std::is_nothrow_swappable_v<T> && std::is_nothrow_move_constructible_v<T>))
(std::is_nothrow_swappable_v<T> && std::is_nothrow_move_constructible_v<T>))
[編輯] 複雜度
與容器大小呈線性關係。
[編輯] 示例
執行此程式碼
#include <inplace_vector> #include <print> int main() { std::inplace_vector<int, 3> a1{1, 2, 3}, a2{4, 5, 6}; auto i1 = a1.begin(); auto i2 = a2.begin(); int& r1 = a1[1]; int& r2 = a2[1]; auto print_them_all = [&](auto rem) { std::println("{}a1 = {}, a2 = {}, *i1 = {}, *i2 = {}, r1 = {}, r2 = {}", rem, a1, a2, *i1, *i2, r1, r2); }; print_them_all("Before swap:\n"); a1.swap(a2); print_them_all("After swap:\n"); // Note that after swap() iterators and references stay associated with their // original sites, e.g., i1 points to element a1[0], r1 refers to a1[1]. }
輸出
Before swap: a1 = [1, 2, 3], a2 = [4, 5, 6], *i1 = 1, *i2 = 4, r1 = 2, r2 = 5 After swap: a1 = [4, 5, 6], a2 = [1, 2, 3], *i1 = 4, *i2 = 1, r1 = 5, r2 = 2
[編輯] 參閱
特化 std::swap 演算法 (函式模板) |