std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::emplace
來自 cppreference.com
template< class... Args > std::pair<iterator, bool> emplace( Args&&... args ); |
(C++11 起) | |
若容器中不存在鍵值與給定 args 所構造的元素相同的元素,則將新元素就地構造並插入容器。
新元素(即 std::pair<const Key, T>)的建構函式被呼叫時,其引數與提供給 emplace
的引數完全相同,並透過 std::forward<Args>(args)... 進行轉發。即使容器中已存在具有該鍵的元素,該元素也可能被構造,在這種情況下,新構造的元素將立即被銷燬(如果不需要此行為,請參閱 try_emplace()
)。
謹慎使用 emplace
允許構造新元素,同時避免不必要的複製或移動操作。
如果操作後新元素的數量大於舊的 max_load_factor()
*
bucket_count()
,則會進行重新雜湊。
如果發生重新雜湊(由於插入),所有迭代器都將失效。否則(沒有重新雜湊),迭代器不會失效。
目錄 |
[編輯] 引數
args | - | 轉發給元素建構函式的引數 |
[編輯] 返回值
一個對,由指向插入元素(或阻止插入的元素)的迭代器和布林值組成,當且僅當插入發生時,布林值設定為 true。
[編輯] 異常
如果由於任何原因丟擲異常,此函式無效果(強異常安全保證)。
[編輯] 複雜度
平均情況下攤銷常數,最壞情況下與容器大小呈線性關係。
[編輯] 示例
執行此程式碼
#include <iostream> #include <string> #include <utility> #include <unordered_map> int main() { std::unordered_map<std::string, std::string> m; // uses pair's move constructor m.emplace(std::make_pair(std::string("a"), std::string("a"))); // uses pair's converting move constructor m.emplace(std::make_pair("b", "abcd")); // uses pair's template constructor m.emplace("d", "ddd"); // emplace with duplicate key has no effect m.emplace("d", "DDD"); // uses pair's piecewise constructor m.emplace(std::piecewise_construct, std::forward_as_tuple("c"), std::forward_as_tuple(10, 'c')); // an alternative is: m.try_emplace("c", 10, 'c'); for (const auto& p : m) std::cout << p.first << " => " << p.second << '\n'; }
可能的輸出
a => a b => abcd c => cccccccccc d => ddd
[編輯] 參閱
使用提示就地構造元素 (public member function) | |
(C++17) |
如果鍵不存在則原地插入,如果鍵存在則不執行任何操作 (public member function) |
插入元素 或節點(C++17 起) (public member function) |