[英]C++ map with 2 keys, such that any 1 key can be used to get the value
I have a use case wherein I have to get a value from a map, given a key.我有一个用例,在给定密钥的情况下,我必须从 map 获取值。 Now the key can be ID (integer) or Name (string).现在键可以是 ID(整数)或名称(字符串)。
I thought about the following structure我想到了以下结构
map1:- ID -> value map1:- ID -> 值
map2:- Name -> ID map2:-名称-> ID
And hide this structure under a common abstraction, so that either name or ID can be used to retrieve the value.并将这个结构隐藏在一个通用的抽象之下,以便可以使用名称或 ID 来检索值。
Is there a better way to do this?有一个更好的方法吗?
Have a look at boost::multi_index
.看看boost::multi_index
。 It allows you to make containers with any combination of lookup that you want.它允许您使用所需的任何查找组合来制作容器。
struct item
{
int ID;
std::string Name;
value_t Value;
};
namespace bmi = boost::multi_index;
using map_t = bmi::multi_index_container<item, bmi::indexed_by<
bmi::unordered_unique<bmi::tag<struct ID>, bmi::member<item, int, &item::ID>>,
bmi::unordered_unique<bmi::tag<struct Name>, bmi::member<item, std::string, &item::Name>>
>>;
map_t Map;
/* add some values */
auto idIt = Map.get<ID>().find(1); // lookup by ID
auto nameIt = Map.get<Name>().find("Vaibhav Gupta"); // lookup by Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.