std::map - 元素访问无异常且无插入 [英] std::map - Element access without exception and without insertion

查看:38
本文介绍了std::map - 元素访问无异常且无插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 std::map 的循环模式.

I have a recurrent pattern with the use of std::map.

我只想在键存在时检索值,否则我不想插入元素.目前我正在使用 count(key)find(key) (哪个更好?从文档中,复杂性似乎相同),如果它们返回一个我访问地图的正值.但是我想避免在地图上使用两个操作.类似的东西:

I want to retrieve the value only when the key is present, otherwise I don't want to insert element. Currently I'm using count(key) or find(key) (which one is better? from the documentation the complexity seems to be the same) and if them returns a positive value that I access the map. However I would like to avoid the use of two operations on the map. Something like:

map<string, int> myMap;
int returnvalue;
boole result = myMap.get("key1",returnValue)
if(result){
  \\ use returnValue
}

阅读关于 cplusplus.com 的 std::map 文档,我发现了两个函数用于访问地图元素:

Reading the std::map documentation on cplusplus.com I found two functions for accessing map elements:

  • at():如果密钥不存在则抛出异常礼物
  • []:如果键不存在
  • at(): which throws an excpetion if the key is not present
  • []: which insert a new value if the key is not present

没有一个能满足我的需要.

None of them satisfy my necessity.

推荐答案

使用 <代码>地图::查找:

auto it = myMap.find(key);

if (it != myMap.end())
{
    // use it->second
}
else
{
    // not found
}

这部分很简单.更难的问题是当你想查找一个元素是否存在并在它存在时返回它,否则在那个键上插入一个新元素,所有这一切都不需要搜索地图两次.为此,您需要使用 lower_bound 后跟提示插入.

This part was easy. The harder problem is when you want to look up if an element exists and return it if it does, but otherwise insert a new element at that key, all without searching the map twice. For that you need to use lower_bound followed by hinted insertion.

这篇关于std::map - 元素访问无异常且无插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆