gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:33:52 25 4
gpt4 key购买 nike

如何使用作为字符串 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com