c++ - 根据值c++从 map 中获取键

标签 c++ stdvector stdmap

我有字符串作为键和 vector 作为值的映射:map<string,vector<int>> myMap;

//("key", value):   
("a", {1})  
("b", {2,3})  
("c", {1})  
("d", {1})  
("e", {2,3}) 
是否可以根据它们的值获取 key ?我想要具有相同值的键,即
(a,c,d) 和 (b,e)。

最佳答案

您必须查看每个元素

std::vector<std::string> keys_matching(const std::map<std::string, std::vector<int>> & map, const std::vector<int> & value) {
    std::vector<std::string> result;
    for (auto & [k, v] : map) {
        if (v == value) {
            result.push_back(k);
        }
    }
    return result;
}

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

相关文章:

C++ HTTP GET 请求问题?

c++ - 如何将这个整数拆分成它的原始值?

java - 客户端-服务器网络入门

c++ - 即使条目相同,也找不到 std::map 键

C++ std::stringstream operator<< 重载

c++ - std::复制失败, "cannot seek vector iterator after end"

c++ - 在std::set中排序的唯一指针

c++ - 为什么将 emplace_back 与已删除的复制构造函数一起使用不起作用?

c++ - 如何将具有常量字段的对象添加到 std::map?

c++ - std::map 的线程安全替代方案?