【问题标题】:Get the first value (string) in a map from the second value (int)从第二个值(int)获取映射中的第一个值(字符串)
【发布时间】:2019-05-14 17:22:57
【问题描述】:

如果你有一个 std::map 接受一个字符串和一个 int。

    std::map<std::string, int> exampleMap;

如果你有正确的int,有什么方法可以打印字符串?

假设我将字符串“hello”和 int 0 插入到我的地图中:

    exampleMap.insert(std::make_pair("hello", 0));

要打印 0,我们可以使用:

    exampleMap.find('hello')->second;

有没有办法打印“hello”字符串?

【问题讨论】:

  • exampleMap.find('hello')-&gt;first 也许?
  • @πάντα ῥε 说什么?
  • 假设我们只有整数可以帮助我们,我们不知道字符串。你能遍历一些整数,看看它们是否附加了一个字符串?
  • 您需要迭代以找到具有正确“第二”的条目以打印“第一”
  • 如果你问“你能不能遍历一堆 int,它们是映射中的值,并找出它们是否有匹配的键?”那么是的,你可以。

标签: c++ dictionary stdmap


【解决方案1】:

您可以依次循环遍历地图中的所有条目,直到找到具有该值的条目:

for (auto &it : exampleMap)
{
    if (it.second == value)
        return it.first;
}

虽然您需要决定如果有多个条目具有相同的 int 值该怎么办,以及如果找不到 int 该怎么办。

【讨论】:

    【解决方案2】:

    你有几个选择...

    1. 创建两个映射(一个从 string 到 int,一个从另一个方向)
    2. 您可以使用"Bi-Directional" map,这样您就可以双向使用。 Boost 还有an implementation
    3. 您可以使用a function like this one 从一张地图转换到另一张地图。

    您选择哪一个取决于您需要进行两次查找的频率。如果很少,我会使用转换功能。如果不是很少见,我会使用双向容器。

    【讨论】:

    • 容器必须强制执行,如果您使用选项 1,这是不可能的。选项 1 不如其他选项。
    • 让我重申这个问题,从 OP 的问题中,您从哪里获得了价值是唯一的信息,您甚至可以强制执行?
    【解决方案3】:

    假设我将字符串“hello”和 int 0 插入到我的地图中:

     exampleMap.insert(std::make_pair("hello", 0));
    

    有没有办法打印“hello”字符串?

    您需要迭代以找到具有预期值的条目以打印密钥

    #include <map>
    #include <string>
    #include <iostream>
    
    int main()
    {
      std::map<std::string, int> exampleMap;
    
      exampleMap.insert(std::make_pair("hello", 0));
      exampleMap.insert(std::make_pair("how", 1));
      exampleMap.insert(std::make_pair("are", 2));
      exampleMap.insert(std::make_pair("you", 0));
    
      int expected = 0;
    
      for (std::map<std::string, int>::const_iterator it = exampleMap.begin();
           it != exampleMap.end();
           ++it) {
        if (it->second == expected)
          std::cout << it->first << std::endl;
      }
    }
    

    编译和执行:

    pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra m.cc
    pi@raspberrypi:/tmp $ ./a.out
    hello
    you
    pi@raspberrypi:/tmp $ 
    

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 2016-08-28
      相关资源
      最近更新 更多