Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map one key, two values

Tags:

c++

stl

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?

like image 973
JonnyCplusplus Avatar asked Apr 06 '11 01:04

JonnyCplusplus


People also ask

Can map have 2 values C++?

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.

Can keys be pairs in maps?

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!

How do you use pairs as values on a map?

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) ) );


2 Answers

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.

like image 128
ildjarn Avatar answered Sep 28 '22 09:09

ildjarn


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.

like image 25
John Zwinck Avatar answered Sep 28 '22 09:09

John Zwinck