名稱空間
變體
操作

std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::try_emplace

來自 cppreference.com
< cpp‎ | 容器‎ | flat map
 
 
 
 
template< class... Args >
std::pair<iterator, bool> try_emplace( const key_type& k, Args&&... args );
(1) (C++23 起)
template< class... Args >
std::pair<iterator, bool> try_emplace( key_type&& k, Args&&... args );
(2) (C++23 起)
template< class K, class... Args >
std::pair<iterator, bool> try_emplace( K&& k, Args&&... args );
(3) (C++23 起)
template< class... Args >
iterator try_emplace( const_iterator hint, const key_type& k, Args&&... args );
(4) (C++23 起)
template< class... Args >
iterator try_emplace( const_iterator hint, key_type&& k, Args&&... args );
(5) (C++23 起)
template< class K, class... Args >
iterator try_emplace( const_iterator hint, K&& k, Args&&... args );
(6) (C++23 起)

如果容器中已存在與 k 等價的鍵,則不做任何操作。否則,將一個新元素插入到底層容器 c 中,鍵為 k,值由 args 構造。

1,2,4,5) 等價於
auto key_it = ranges::upper_bound(c.keys, k, compare);
auto value_it = c.values.begin() + std::distance(c.keys.begin(), key_it);
c.keys.insert(key_it, std::forward<decltype(k)>(k));
c.values.emplace(value_it, std::forward<Args>(args)...);
3,6) 等價於
auto key_it = ranges::upper_bound(c.keys, k, compare);
auto value_it = c.values.begin() + std::distance(c.keys.begin(), key_it);
c.keys.emplace(key_it, std::forward<K>(k));
c.values.emplace(value_it, std::forward<Args>(args)...);
kkey_type 的轉換必須構造一個物件 u,使得 find(k) == find(u)true。否則,行為未定義。
這些過載僅在以下條件之一滿足時參與過載決議:

目錄

[edit] 引數

k - 用於查詢和插入(如果未找到)的鍵
hint - 指向新元素將插入位置之前的迭代器
args - 轉發給元素建構函式的引數

[edit] 返回值

1-3)emplace 相同。
4-6)emplace_hint 相同。

[edit] 複雜度

1-3)emplace 相同。
4-6)emplace_hint 相同。

[edit] 注意

insertemplace 不同,這些函式在不發生插入時不會移動右值引數,這使得操作值為僅可移動型別的對映變得容易,例如 std::flat_map<std::string, std::unique_ptr<foo>>。此外,try_emplace 分別處理鍵和 mapped_type 的引數,這與 emplace 不同,後者要求引數構造一個 value_type(即 std::pair)。

過載 (3,6) 可以在不構造 key_type 型別物件的情況下呼叫。

[edit] 示例

#include <flat_map>
#include <iostream>
#include <string>
#include <utility>
 
void print_node(const auto& node)
{
    std::cout << '[' << node.first << "] = " << node.second << '\n';
}
 
void print_result(auto const& pair)
{
    std::cout << (pair.second ? "inserted: " : "ignored:  ");
    print_node(*pair.first);
}
 
int main()
{
    using namespace std::literals;
    std::map<std::string, std::string> m;
 
    print_result(m.try_emplace( "a", "a"s));
    print_result(m.try_emplace( "b", "abcd"));
    print_result(m.try_emplace( "c", 10, 'c'));
    print_result(m.try_emplace( "c", "Won't be inserted"));
 
    for (const auto& p : m)
        print_node(p);
}

輸出

inserted: [a] = a
inserted: [b] = abcd
inserted: [c] = cccccccccc
ignored:  [c] = cccccccccc
[a] = a
[b] = abcd
[c] = cccccccccc

[edit] 參閱

就地構造元素
(public member function) [edit]
使用提示就地構造元素
(public member function) [edit]
插入元素
(public member function) [edit]
插入元素或如果鍵已存在則賦值給當前元素
(public member function) [edit]