当映射包含字符串向量作为值时,从值中获取键的有效方法

Efficient way to get key from value when map contain vector of string as value

本文关键字:获取 方法 有效 包含 映射 字符串 向量      更新时间:2023-10-16

如何使用字符串向量的值获取密钥,反之亦然。下面是我的代码。

#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_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;
}

密钥存储在pair.first中。如果您的用例处于循环迭代中,只需使用它,如图所示。

如果你的意思是在任何使用中,没有迭代,也就是说,给定一个值获取关联的键,没有直接的方法可以做到这一点。您可以为每个值构建反向映射到键,但考虑到您还需要唯一值的事实,这不会真正有效。

为每个矢量条目创建另一张相反的地图?

如果数组条目不唯一,则需要执行相同的映射到向量,或使用多映射。

还可以考虑使用哈希映射 (unordered_map( 和 stringview 作为减少第二个映射的内存使用的方法?

但最好的答案是增强的 2 向地图,对不起。您可以将这两个映射包装在您自己的类中,该类公开了双向映射的功能。