如何使用map :: find在地图上

时间:2019-07-17 12:07:35

标签: c++

在大型代码库中进行一些单元测试时遇到问题。基本上,我需要在地图map中找到一个值。我写了一段代码来解释我的问题是什么。下面显示了数据的构建方式:

map<string, map<string, string>> testmap;
map<string, string> item;
item.insert(pair<string,string>("hello","world"));
testmap.insert(pair<string, map<string,string> > ("key",item));

然后,在以后的某个时间点,我需要在获取密钥之前检查是否已添加了值。从cppreference中,[]运算符的返回为

  

如果没有元素与新元素的映射值引用   密钥存在。否则,将引用   键等于键的现有元素。

如果我正确理解(从注释中可以清楚地表明我不是),则意味着如果没有带有该键的元素,则会插入一个新元素。我想避免这种情况,并返回错误消息。

以下是错误,我正试图了解原因:

if (testmap.find(map<string,string>("hello","world")) != testmap.end()) 
{
    ...
    return testmap["hello"]["world"];
}

2 个答案:

答案 0 :(得分:3)

要在映射中查找值,不能使用find成员函数来查找键。但是,您可以找到一个值,例如,通过将std::find_if与自定义比较器一起使用:

using value_t = std::map<std::string, std::string>;
using key_t = std::string;
using map_t = std::map<key_t, value_t>;

map_t m { { "key" , { { "hello", "world" } } } };

value_t v { { "hello", "world" } };  // value to be found
auto iter = std::find_if(m.begin(), m.end(),
               [&v](const auto& e){ return e.second == v; });
std::cout << (iter != m.end()) << std::endl;

实时演示:https://wandbox.org/permlink/1b0bjbnnPY8E0uiU


请注意,这将从C ++ 14开始生效。在C ++ 11中,您需要编写:

auto iter = std::find_if(m.begin(), m.end(),
               [&v](const map_t::value_type& e){ return e.second == v; });

更新

我仍然不清楚您要达到的目标。如果仅在两个级别的键都存在时才需要引用最内层的值,则可以这样做(C ++ 17语法):

if (auto i1 = m.find("key"); i1 != m.end())
   if (auto i2 = i1->second.find("hello"); i2 != i1->second.end())
      std::cout << i2->second << std::endl;  // same as m["key"]["hello"] here but faster

答案 1 :(得分:1)

在我看来,您想要的是testmap.find("key"),即搜索密钥,但是由于某种原因,您认为应该搜索价值...

相关问题