Using pair as key in a map (C++ / STL)

ccarpenterg picture ccarpenterg · Jul 18, 2010 · Viewed 75.1k times · Source

I want to use a pair from STL as a key of a map.

#include <iostream>
#include <map>

using namespace std;

int main() {

typedef pair<char*, int> Key;
typedef map< Key , char*> Mapa;

Key p1 ("Apple", 45);
Key p2 ("Berry", 20);

Mapa mapa;

mapa.insert(p1, "Manzana");
mapa.insert(p2, "Arandano");

return 0;

}

But the compiler throw a bunch of unreadable information and I'm very new to C and C++.

How can I use a pair as a key in a map? And in general How can I use any kind of structure (objects, structs, etc) as a key in a map?

Thanks!

Answer

James McNellis picture James McNellis · Jul 18, 2010

std::map::insert takes a single argument: the key-value pair, so you would need to use:

mapa.insert(std::make_pair(p1, "Manzana"));

You should use std::string instead of C strings in your types. As it is now, you will likely not get the results you expect because looking up values in the map will be done by comparing pointers, not by comparing strings.

If you really want to use C strings (which, again, you shouldn't), then you need to use const char* instead of char* in your types.

And in general How can I use any kind of structure (objects, structs, etc) as a key in a map?

You need to overload operator< for the key type or use a custom comparator.