我是靠谱客的博主 自由过客,这篇文章主要介绍c++17中map的try_emplace与insert_or_assign方法c++17中map的try_emplace与insert_or_assign,现在分享给大家,希望可以做个参考。

c++17中map的try_emplace与insert_or_assign

try_emplace

函数原型:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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

insertemplace不同,如果插入没有发生,这些函数不会从右值参数移动,提升效率!

代码示例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

函数原型:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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一样

代码示例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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; }

如果本文对你有帮助,记得一键三连哦,一键三连笑哈哈,代码能力顶呱呱!

本人能力有限,如有错误,望不吝指正;原创不易,欢迎转载,转载请注明出处!

最后

以上就是自由过客最近收集整理的关于c++17中map的try_emplace与insert_or_assign方法c++17中map的try_emplace与insert_or_assign的全部内容,更多相关c++17中map内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部