在线文档教程
C++
容器 | Containers

std::map::try_emplace

STD::地图::[医]座落

template pair try_emplace(const key_type& k, Args&&... args(1)(since C++17)
template <class... Args> pair<iterator, bool> try_emplace(key_type&& k, Args&&... args(2)(since C++17)
template <class... Args> iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args(3)(since C++17)
template <class... Args> iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args(4)(since C++17)

1%29如果密钥相当于k已经存在于容器中,什么都不做。否则,行为就像座落但元素构造为value_type(std::piecewise_construct, std::forward_as_tuple(k), std::forward_as_tuple(forward<Args>(args)...))

2%29如果密钥相当于k已经存在于容器中,什么都不做。否则,行为就像座落但元素构造为value_type(std::piecewise_construct, std::forward_as_tuple(std::move(k)), std::forward_as_tuple(forward<Args>(args)...))

3%29如果密钥相当于k已经存在于容器中,什么都不做。否则,行为就像座落[医]暗示但元素构造为value_type(std::piecewise_construct, std::forward_as_tuple(k), std::forward_as_tuple(forward<Args>(args)...))

4%29如果密钥相当于k已经存在于容器中,什么都不做。否则,行为就像座落[医]暗示但元素构造为value_type(std::piecewise_construct, std::forward_as_tuple(std::move(k)), std::forward_as_tuple(forward<Args>(args)...))

没有迭代器或引用无效。

参数

k-the key used both to look up and to insert if not found
hint-iterator to the position before which the new element will be inserted
args-arguments to forward to the constructor of the element

返回值

1,2%29与座落

3.4%29与座落[医]暗示

复杂性

1,2%29与座落

3.4%29与座落[医]暗示

注记

不像插入或座落,如果不进行插入,则这些函数不会从rvalue参数中移动,这使得操作其值为仅移动类型的映射变得容易,例如std::map<std::string, std::unique_ptr<foo>>.此外,try_emplace对象的键和参数。mapped_type分别,不像座落,它需要参数来构造value_type%28,即astd::pair29%。

二次

#include <iostream> #include <utility> #include <string> #include <map> int main() { using namespace std::literals; std::map<std::string, std::string> m; m.try_emplace("a", "a"s m.try_emplace("b", "abcd" m.try_emplace("c", 10, 'c' for (const auto &p : m) { std::cout << p.first << " => " << p.second << '\n'; } }

二次

产出:

二次

a => a b => abcd c => cccccccccc

二次

另见

emplace (C++11)constructs element in-place (public member function)
emplace_hint (C++11)constructs elements in-place using a hint (public member function)
insertinserts elements or nodes (since C++17) (public member function)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/容器/map/try[医]座落