其他分享
首页 > 其他分享> > c – 当map包含string的向量作为值时,从值获取键的有效方法

c – 当map包含string的向量作为值时,从值获取键的有效方法

作者:互联网

如何使用值作为字符串向量来获取密钥,反之亦然.以下是我的代码.

#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 ?
        }}
}

情况1:输入值时.键输出.

Input  : goodmorning
output : unique2

情况2:当输入键时输出值.

Input : unique3
output: sun ,mon ,tue

注意:没有可用的增强库.

解决方法:

对于案例1,find_if和any_of的组合将完成这项工作.

对于案例2,您只需使用unordered_map的find方法即可.

#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,c11,stdmap
来源: https://codeday.me/bug/20190827/1746175.html