如何从地图中获取价值? [英] How can I get a value from a map?

查看:50
本文介绍了如何从地图中获取价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 valueMap map ,如下所示:

  typedef std :: map< std :: string,std :: string> MAP;MAP valueMap;...//输入数据. 

然后我将该地图通过引用传递给函数:

  void函数(const MAP& map){std :: string value = map ["string"];//这样,我得到一个错误.} 

如何从映射中获取值,该值作为对函数的引用而传递?

解决方案

不幸的是, std :: map :: operator [] 是非常量成员函数,并且您有一个const引用./p>

您需要更改 function 的签名,或者执行以下操作:

  MAP :: const_iterator pos = map.find("string");如果(pos == map.end()){//处理错误} 别的 {std :: string value = pos-> second;...} 

operator [] 通过向映射添加默认构造的值并返回对其的引用来处理错误.当您只有一个const引用时,这是没有用的,因此您需要做一些不同的事情.

如果程序逻辑以某种方式保证了,您可以忽略这种可能性,并编写 string value = map.find("string")-> second; >字符串" 已经是一个密钥.显而易见的问题是,如果您输入错误,则会得到不确定的行为.

I have a map named valueMap as follows:

typedef std::map<std::string, std::string>MAP;
MAP valueMap;
...
// Entering data.

Then I am passing this map to a function by reference:

void function(const MAP &map)
{
  std::string value = map["string"];
  // By doing so I am getting an error.
}

How can I get the value from the map, which is passed as a reference to a function?

解决方案

Unfortunately std::map::operator[] is a non-const member function, and you have a const reference.

You either need to change the signature of function or do:

MAP::const_iterator pos = map.find("string");
if (pos == map.end()) {
    //handle the error
} else {
    std::string value = pos->second;
    ...
}

operator[] handles the error by adding a default-constructed value to the map and returning a reference to it. This is no use when all you have is a const reference, so you will need to do something different.

You could ignore the possibility and write string value = map.find("string")->second;, if your program logic somehow guarantees that "string" is already a key. The obvious problem is that if you're wrong then you get undefined behavior.

这篇关于如何从地图中获取价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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