std::map try_emplace() 方法
- 自 C++17 起
// (1) Non const version only
template< class... Args >
pair<iterator, bool> try_emplace( const Key& k, Args&&... args );
// (2) Non const version only
template< class... Args >
pair<iterator, bool> try_emplace( Key&& k, Args&&... args );
// (3) Non const version only
template< class... Args >
iterator try_emplace( const_iterator hint, const Key& k, Args&&... args );
// (4) Non const version only
template< class... Args >
iterator try_emplace( const_iterator hint, Key&& k, Args&&... args );
如果容器中没有键为 k
的元素,则将一个新元素插入容器,其键为 k
,值通过 args
构造。
- (1) 如果容器中已经存在与
k
等效的键,则不执行任何操作。否则,其行为类似于emplace()
,但元素构造方式如下:
value_type(std::piecewise_construct,
std::forward_as_tuple(k),
std::forward_as_tuple(std::forward<Args>(args)...))
- (2) 如果容器中已经存在与
k
等效的键,则不执行任何操作。否则,其行为类似于emplace()
,但元素构造方式如下:
value_type(std::piecewise_construct,
std::forward_as_tuple(std::move(k)),
std::forward_as_tuple(std::forward<Args>(args)...))
- (3) 如果容器中已经存在与
k
等效的键,则不执行任何操作。否则,其行为类似于emplace_hint()
,但元素构造方式如下:
value_type(std::piecewise_construct,
std::forward_as_tuple(k),
std::forward_as_tuple(std::forward<Args>(args)...))
- (4) 如果容器中已经存在与
k
等效的键,则不执行任何操作。否则,其行为类似于emplace_hint()
,但元素构造方式如下:
value_type(std::piecewise_construct,
std::forward_as_tuple(std::move(k)),
std::forward_as_tuple(std::forward<Args>(args)...))
不使任何迭代器或引用失效。
参数
k
- 用于查找和(如果未找到)插入的键hint
- 指向新元素将插入位置之前的迭代器args
- 转发给元素构造函数的参数
返回值
- (1-2) 与
emplace()
相同。 - (3-4) 与
emplace_hint()
相同。
复杂度
- (1-2) 与
emplace()
相同。 - (3-4) 与
emplace_hint()
相同。
异常
如果任何操作抛出异常,此函数不产生任何影响(强异常保证)。
备注
与 insert()
或 emplace()
不同,如果未发生插入,这些函数不会从右值参数移动,这使得操作值为仅可移动类型的映射(例如 std::map<std::string, std::unique_ptr<foo>>
)变得容易。此外,try_emplace()
分别处理键和 mapped_type
的参数,这与 emplace 不同,后者需要参数来构造一个 value_type(即 std::pair
)。
特性测试宏:__cpp_lib_map_try_emplace
。
示例
Main.cpp
#include <iostream>
#include <utility>
#include <string>
#include <map>
auto print_node = [](const auto &node) {
std::cout << "[" << node.first << "] = " << node.second << '\n';
};
auto 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