c++ - 如何从 map 中获取值?

标签 c++ dictionary stdmap

我有一个名为valueMapmap如下:

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

然后我通过引用将此映射传递给函数:

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

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

最佳答案

std::map::operator[] 是一个非常量成员函数,并且你有一个 const 引用。

您要么需要更改 function 的签名,要么:

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

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

可以忽略这种可能性并写string value = map.find("string")->second;,如果你的程序逻辑以某种方式保证 "string" 已经是一个键。明显的问题是,如果你错了,你就会得到未定义的行为。

关于c++ - 如何从 map 中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10699689/

相关文章:

python - 如何使用任意长度的键更新 python 字典?

c++ - 返回 map 循环的问题

c++ - 序列化 std::map C++

c++ - Cuda ORB 描述符 Opencv

c++ - 如何将 stderr 与输出流相关联

python - 随机重新排序字典

c++ - 当我应该使用 std::map::at 来检索 map 元素时

c++ - 为什么我的 Woodall 数计算程序在 n >47 后产生错误的结果?

c++ - 按列主要顺序重新排序 3D vector 三元组很慢

java - 对多个函数执行相同的操作