我正在使用Boost unordered_map.我为每个条目都有一个键值对.如何确定地图中是否存在特定值?(我不想创建另一个unordered_map,它将值存储为键,键作为值存储)
谢谢.
小智 11
以下内容如何:
typedef std::unordered_map<int,std::string> map_type;
typedef std::unordered_map<int,std::string>::value_type map_value_type;
map_type m;
if (m.end() != find_if(m.begin(),m.end(),[](const map_value_type& vt)
{ return vt.second == "abc"; }
))
std::cout << "Value found." << std::end;
else
std::cout << "Value NOT found." << std::end;
Run Code Online (Sandbox Code Playgroud)
或者使用捕获的外部变量:
std::string value = "abc";
if (m.end() != find_if(m.begin(),m.end(),[&value](const map_value_type& vt)
{ return vt.second == value; }))
std::cout << "Value found." << std::end;
else
std::cout << "Value NOT found." << std::end;
Run Code Online (Sandbox Code Playgroud)
您需要遍历所有元素unordered_map并查看给定值是否存在.
std::find_if具有自定义谓词的算法可用于简化此操作.