c++ - 当映射包含字符串 vector 作为值时从值中获取键的有效方法

标签 c++ c++11 stdmap

如何使用作为字符串 vector 的值获取键,反之亦然。下面是我的代码。

#include<iostream>
#include<map>
#include<string>
#include <unordered_map>
#include <vector>

using namespace std;
int main()
{
std::unordered_map<std::string, std::vector<std::string>> Mymap;
Mymap["unique1"] = {"hello", "world"};
Mymap["unique2"] = {"goodbye", "goodmorning", "world"};
Mymap["unique3"] = {"sun", "mon", "tue"};

for(auto && pair : Mymap) {
        for(auto && value : pair.second) {
                std::cout << pair.first<<" " << value<<"\n";
                if(value == "goodmorning") // how get key i.e unique2 ?
        }}
}

情况一:输入值时。关键是输出。

Input  : goodmorning
output : unique2

case 2:key为input,value为output。

Input : unique3
output: sun ,mon ,tue

注意:没有可用的 boost 库。

最佳答案

对于情况 1,find_ifany_of 的组合将完成这项工作。

对于情况 2,您可以简单地使用 unordered_mapfind 方法。

#include<iostream>
#include<map>
#include<string>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    unordered_map<string, vector<string>> Mymap;
    Mymap["unique1"] = { "hello", "world" };
    Mymap["unique2"] = { "goodbye", "goodmorning", "world" };
    Mymap["unique3"] = { "sun", "mon", "tue" };

    // Case 1

    string test_value = "goodmorning";
    auto iter1 = find_if(Mymap.begin(), Mymap.end(),
        [&test_value](const decltype(*Mymap.begin()) &pair)
        {
            return any_of(pair.second.begin(), pair.second.end(), [&test_value](const string& str) { return str == test_value; });
        });

    if (iter1 != Mymap.end())
    {
        cout << "Key: " << iter1->first << endl;
    }
    else
    {
        cout << "No key found for " << test_value;
    }

    // Case 2

    test_value = "unique3";
    auto iter2 = Mymap.find(test_value);
    if (iter2 != Mymap.end())
    {
        int first = true;
        for (auto v : iter2->second)
        {
            cout << (first ? "" : ", ") << v;
            first = false;
        }
        cout << endl;
    }
    else
    {
        cout << "No value found for key " << test_value << endl;
    }

    return 0;
}

关于c++ - 当映射包含字符串 vector 作为值时从值中获取键的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52535347/

相关文章:

c++ - 使用 json c++ 的输出在字段中获取奇怪的字符

键和文件的 C++ 映射不起作用

c++ - STL中的调试错误

c++ - Sprite 表动画期间闪烁

c++ - 从字符串列表中找到最快的字符串

c++ - std::array 中使用的 C++ 11 中的全局常量

c++ - 简单的 C++ 声音 API

c++ - CLion 禁用 C++98 模式以支持 C++11

c++ - 在 STL 映射中,使用 map::insert 比使用 [] 更好吗?

c++ - 使用对象作为键时保持 std::map 平衡