【问题标题】:How to check is there an element in map values [closed]如何检查地图值中是否有元素[关闭]
【发布时间】:2018-09-03 20:16:56
【问题描述】:

有一个mapmap<string, vector<string>> buses; 结构,我有一个string,所以我需要了解如何检查string 包含在map 向量中。

string stop;
cin >> stop;

if (buses.find(stop) != buses.end()) {
    cout << "Yes";
} else {
    cout << "No";
}

当我得到一个stop 字符串时,我需要检查map 的值(不是键,更准确地说是map.second)中是否有一个字符串等于stop 字符串,如果是,我需要打印出所有值中包含stop 元素的键。 { {"bus#1", {"stop#1", "stop#2", "stop#3"}}, ... }

【问题讨论】:

  • 你的意思是“我能找出地图中是否有一个给定字符串的键吗?如果有,find 应该这样做。你能举一个完整的例子吗?
  • 你能说明buses的定义(和人口)吗?
  • @StephanLechner 已编辑
  • 我确定他的地图是{ {"bus#1", {"stop#1", "stop#2", "stop#3"}}, ... },所以他需要先构建一个反向地图或在嵌套循环中进行查找。
  • 听起来你需要反转你的键值对并使用find

标签: c++


【解决方案1】:

一种方法是遍历所有地图元素,然后在值向量上使用std::find。但这确实效率低下。

相反,您应该使用std::multimap&lt;std::string, std::string&gt;(或std::unordered_multimap,如果您不需要排序)并使用停止作为键。然后在该键中添加使用所述停靠点的所有公共汽车,如果您想获取该停靠点的所有公共汽车,请使用 find

【讨论】:

    【解决方案2】:

    我想这就是你想要做的。

    #include <map>
    #include <iostream>
    #include <vector>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        map<string, vector<string>> buses;
    
        buses["some stop"] = vector<string>();
    
        if (buses.find("some stop") != buses.end()) {
            cout << "Yes";
        }
        else {
            cout << "No";
        }
    }
    

    您确定map 是您要用于此任务的数据结构吗?

    否则,如果您只想查看停靠点是否在数据结构中,则可能需要查看 std::set

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-08
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 2018-08-03
      相关资源
      最近更新 更多