std::multimap<Key,T,Compare,Allocator>::swap
來自 cppreference.com
void swap( multimap& other ); |
(C++17 前) | |
void swap( multimap& other ) noexcept(/* 見下方 */); |
(C++17 起) | |
將容器的內容與 other 的內容交換。不呼叫任何單個元素的移動、複製或交換操作。
所有迭代器和引用保持有效。end()
迭代器失效。Compare
物件必須是可交換的 (Swappable),它們透過對非成員函式 swap
的非限定呼叫進行交換。
若 std::allocator_traits<allocator_type>::propagate_on_container_swap::value 為 true,則分配器透過對非成員函式 |
(C++11 起) |
目錄 |
[編輯] 引數
其他 | - | 用於交換內容的容器 |
[編輯] 異常
由 |
(C++17 前) |
noexcept 規範:
noexcept(std::allocator_traits<Allocator>::is_always_equal::value && std::is_nothrow_swappable<Compare>::value) |
(C++17 起) |
[編輯] 複雜度
常數時間。
[編輯] 示例
執行此程式碼
#include <iostream> #include <string> #include <utility> #include <map> // print out a std::pair template<class Os, class U, class V> Os& operator<<(Os& os, const std::pair<U, V>& p) { return os << p.first << ':' << p.second; } // print out a container template<class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << '{'; for (auto const& i : co) os << ' ' << i; return os << " }\n"; } int main() { std::multimap<std::string, std::string> m1{{"γ", "gamma"}, {"β", "beta"}, {"α", "alpha"}, {"γ", "gamma"}}, m2{{"ε", "epsilon"}, {"δ", "delta"}, {"ε", "epsilon"}}; const auto& ref = *(m1.begin()); const auto iter = std::next(m1.cbegin()); std::cout << "──────── before swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; m1.swap(m2); std::cout << "──────── after swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; // Note that every iterator referring to an element in one container before // the swap refers to the same element in the other container after the swap. // Same is true for references. }
輸出
──────── before swap ──────── m1: { α:alpha β:beta γ:gamma γ:gamma } m2: { δ:delta ε:epsilon ε:epsilon } ref: α:alpha iter: β:beta ──────── after swap ──────── m1: { δ:delta ε:epsilon ε:epsilon } m2: { α:alpha β:beta γ:gamma γ:gamma } ref: α:alpha iter: β:beta
[編輯] 參閱
特化 std::swap 演算法 (函式模板) |