std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::emplace
來自 cppreference.com
template< class... Args > std::pair<iterator, bool> emplace( Args&&... args ); |
(C++23 起) | |
若容器中不存在鍵值與給定 args 所構造的元素相同的元素,則將新元素就地構造並插入容器。
使用 std::forward<Args>(args)... 初始化型別為 std::pair<key_type, mapped_type> 的物件 t;如果對映中已包含一個鍵等同於 t.first 的元素,則 *this 不變。否則,等同於
auto key_it = ranges::upper_bound(c.keys, t.first, compare); auto value_it = c.values.begin() + std::distance(c.keys.begin(), key_it); c.keys.insert(key_it, std::move(t.first)); c.values.insert(value_it, std::move(t.second));
僅當 std::is_constructible_v<std::pair<key_type, mapped_type>, Args...> 為 true 時,此過載才參與過載決議。
謹慎使用 emplace
允許構造新元素,同時避免不必要的複製或移動操作。
迭代器失效資訊從 此處 複製 |
目錄 |
[編輯] 引數
args | - | 轉發給元素建構函式的引數 |
[編輯] 返回值
一個對,由指向被插入元素(或阻止插入的元素)的迭代器以及一個 bool 值組成,該值僅當插入發生時才設定為 true。
[編輯] 異常
如果由於任何原因丟擲異常,此函式無效果(強異常安全保證)。
[編輯] 複雜度
如果發生插入,則與容器大小呈線性關係,否則與容器大小呈對數關係
[編輯] 示例
執行此程式碼
#include <iostream> #include <string> #include <utility> #include <flat_map> int main() { std::flat_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) | |
如果鍵不存在則原地插入,如果鍵存在則不執行任何操作 (public member function) | |
插入元素 (public member function) |