c++17中map的try_emplace与insert_or_assign
try_emplace
函数原型:
template <class... Args>
pair<iterator, bool> 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)
如果容器中已经存在等效的键,则不执行任何操作。否则,其行为类似于emplace 。
与insert 或emplace 不同,如果插入没有发生,这些函数不会从右值参数移动,提升效率!
代码示例:
map<int, string> cities = {
{1, "beijing"},
{2, "shanghai"},
{3, "hangzhou"},
pair<int, string>(4, "tianjin"),
make_pair(5, "chengdu")};
auto [iterator, inserted] = cities.try_emplace(1, "shenzhen");
if (inserted)
{
cout << "insert ok!" << endl;
}
else
{
cout << "error insert" << endl;
}
insert_or_assign
函数原型:
template <class M>
pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj);
(1) (since C++17)
template <class M>
pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj);
(2) (since C++17)
template <class M>
iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj);
(3) (since C++17)
template <class M>
iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj);
(4) (since C++17)
如果容器中已经存在等效的键,则更新key的value,否则,插入新值,和insert一样
代码示例:
map<int, string> cities = {
{1, "beijing"},
{2, "shanghai"},
{3, "hangzhou"},
pair<int, string>(4, "tianjin"),
make_pair(5, "chengdu")};
auto [iterator, inserted] = cities.insert_or_assign(1, "shenzhen");
if (inserted)
{
cout << "insert ok!" << endl;
}
else
{
cout << "error insert" << endl;
}
for (const auto &[cityNum, cityName] : cities)
{
cout << cityNum << ":" << cityName << endl;
}
如果本文对你有帮助,记得一键三连哦,一键三连笑哈哈,代码能力顶呱呱!
本人能力有限,如有错误,望不吝指正;原创不易,欢迎转载,转载请注明出处!
|