slin6174
slin6174

Reputation: 108

Mapping different keys to the same value in c++

So I searched around and found that we can use multi-map to map a set of equivalent keys to different values. I am wondering how to do the reverse? That is to map different keys to the same value? Is there a stl data structure for that?

Upvotes: 5

Views: 11243

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

A normal std::map (or std::unordered_map) can do that. You have a few choices on how to do that:

  • Normal key-value store, where you copy the values as needed
  • Normal key-value store, but where the value is a pointer to the actual data that can be shared, optionally using a std::shared_ptr
  • Use some kind of structure (a std::tuple perhaps) to collect the keys (though it's probably more trouble handling this than it's worth, nothing I really recommend)
  • Use Boost multi-index containers

With Boost you have a ready solution that you can just use, and if you already use Boost in your project (it is a great set of libraries, and complements the standard library well) I think it's a no-brainer to pick that solution.

Upvotes: 8

R Sahu
R Sahu

Reputation: 206577

You can have a std::map such that multiple keys map to the same value. There is nothing against that. However, what you are probably looking for is the ability to to find all the keys that map to a given value without iterating over the entire map. I don't think there is any such data structure for that.

Upvotes: 1

Related Questions