std::array<T,N>::swap
來自 cppreference.com
void swap( array& other ) noexcept(/* 見下文 */); |
(C++11 起) (C++20 起為 constexpr) |
|
將容器的內容與 other 的內容進行交換。這不會導致迭代器和引用與另一個容器關聯。
目錄 |
[編輯] 引數
其他 | - | 用於交換內容的容器 |
[編輯] 返回值
(無)
[編輯] 異常
noexcept 規範:
noexcept(noexcept(swap(std::declval<T&>(), std::declval<T&>()))) 在上述表示式中,識別符號 |
(C++17 前) |
noexcept 規範:
noexcept(std::is_nothrow_swappable_v<T>) |
(C++17 起) |
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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2456 | C++11 | noexcept 規範格式錯誤 |
已修復 |
[編輯] 另請參閱
(C++11) |
特化 std::swap 演算法 (函式模板) |