tags:

views:

68

answers:

3

I need to have a map like this :

typedef std::map<int, float , char> Maptype ;

What is the syntax to insert and searching elements of pair in this map.

+6  A: 

A map can only map one key type to one data type. If the data contains 2 elements, use a struct or a std::pair.

typedef std::map<int, std::pair<float, char> > Maptype;
...
Maptype m;
m[123] = std::make_pair(0.5f, 'c');
...
std::pair<float, char> val = m[245];
std::cout << "float: " << val.first << ", char: " << val.second << std::endl;
KennyTM
Avoid copying the pair out of the map by assigning a reference:std::pair<float, char>
David Smith
+3  A: 

You cannot have three elements. The STL map stores a key-value pair. You need to decide on what you are going to use as a key. Once done, you can probably nest the other two in a separate map and use it as:

typedef std::map<int, std::map<float, char> > MapType;

In order to insert in a map, use the operator[] or the insert member function. You can search for using the find member function.

MapType m;
// insert
m.insert(std::make_pair(4, std::make_pair(3.2, 'a')));
m[ -4 ] = make_pair(2.4, 'z');
// fnd
MapType::iterator i = m.find(-4);
if (i != m.end()) { // item exists ...
}

Additionally you can look at Boost.Tuple.

dirkgently
Thanks for info . How do I search for the pair in Map .Will it be m.find(STD::make_pair(3.2,'a'); ?
John
@John: You search for the key, always. If your key is of type `pair<float, char>` then that is what you pass as argument to `map::find`. Note, in a map, the first parameter is the key, the second is the key's value. Either, can be a complex type. However, the key is always `const` and can not be assigned to.
dirkgently
+2  A: 

Use either

std::map<std::pair<int, float>, char>

or

std::map<int, std::pair<float, char> >

whichever is correct.

avakar
Note that the former would need either an overloaded `operator<` or a function object for sorting passed to the map.
sbi
std::pair already has operator< (it does lexicographical comparison).
Tronic
@Tronic: Does it? <blush>
sbi