I have a use case wherein I have to get a value from a map, given a key. Now the key can be ID (integer) or Name (string).
I thought about the following structure
map1:- ID -> value
map2:- Name -> ID
And hide this structure under a common abstraction, so that either name or ID can be used to retrieve the value.
Is there a better way to do this?
Have a look at 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.