当映射包含字符串向量作为值时,从值中获取键的有效方法
Efficient way to get key from value when map contain vector of string as value
如何使用字符串向量的值获取密钥,反之亦然。下面是我的代码。
#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;
}
密钥存储在pair.first
中。如果您的用例处于循环迭代中,只需使用它,如图所示。
如果你的意思是在任何使用中,没有迭代,也就是说,给定一个值获取关联的键,没有直接的方法可以做到这一点。您可以为每个值构建反向映射到键,但考虑到您还需要唯一值的事实,这不会真正有效。
为每个矢量条目创建另一张相反的地图?
如果数组条目不唯一,则需要执行相同的映射到向量,或使用多映射。
还可以考虑使用哈希映射 (unordered_map( 和 stringview 作为减少第二个映射的内存使用的方法?
但最好的答案是增强的 2 向地图,对不起。您可以将这两个映射包装在您自己的类中,该类公开了双向映射的功能。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 获取从C++中同一类中的构造函数调用的方法返回的值
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 如何从ECS中的模板方法获取组件?
- 如何在没有实例的情况下获取非静态方法的类型?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 如何使用 C/C++ 和 system() 系统调用以外的其他方法在 Linux 中获取文件功能?
- 获取第一个模板参数的可靠方法
- 从 c++ 中的实例化进程获取输出的可靠方法是什么?
- 在 c++ 中从执行的 shell 命令获取返回状态的安全方法是什么?
- 在 c++ 中为我的类设置/获取方法时遇到问题
- 从C 中的VTable获取方法指针
- 从成员函数指针获取方法的返回类型
- 获取方法上的代码崩溃,C++
- 如何在类中获取方法的地址?
- 从 twitcurl 时间线获取未授权错误用户获取方法
- 如何制作一个好的设置/获取方法
- 如何获取方法内部int数组(方法参数)的长度
- cocos2d-x中文件路径的获取方法