What is the best way to map two values to one key?
ie An item with a value and bool.
Tried using:
std::map<std::string, std::pair<std::string, bool> > myMap2
But that doesn't seem like the correct solution. Is there a more elegant way to do this?
The C++ STL map is an associative map between a single key and a single value. In addition, the key must be unique for the given map. The C++ STL also provides a multimap template, which removes the unique key restriction. A single key in a multimap can map to multiple values.
Do you mean cout << mymap[make_pair(1,2)] << endl; ? (1,2) is non-sensical, at least in this context. You must have an std::pair to be used as your key, and that means following what @andre just commented. Yes!
The std::map operator[] returns a reference to the map element identified by 100 (key), which is then overwritten by the pair returned by std::make_pair(10,10). I would suggest: map. insert( std::make_pair( 100, std::make_pair(10,10) ) );
That is indeed the correct solution. More generally, consider using std::tuple instead of std::pair for a uniform interface regardless of the number of values (as std::pair is obviously restricted to two), or boost::tuple if your compiler is too old to ship with a std:: or std::tr1:: implementation.
Either use std::pair<> as you did, or make a custom struct containing the values you want to store. I'd do the latter in most cases, as the values then have names more descriptive than first and second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With