如何从地图中获取价值? [英] How can I get a value from a map?
问题描述
我有一个名为 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屋!