tags:

views:

223

answers:

1

Hello,

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!

+8  A: 

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.

James McNellis
`mapa[p1] = "Manzana";` is even shorter
Peter G.
@Peter: `operator[]` has different semantics, and I'd recommend against using it for inserting objects into a `map` (it inserts a new object if one does not already exist, then overwrites the newly created temporary object immediately).
James McNellis
@James: Wow That was an ugly mistake, I forgot to make the pair. I'm sorry!Well it works now but it didn't work when I was using char* instead of const char*. What's the deal with const char* vs char* in this case? Thanks!
ccarpenterg
@ccarpenterg: No need to apologize to me. :-) The string literals have a type `const char[]`, the pair type has a member of type `char*`; the pair constructor cannot remove the const qualifier. That said; really: use `std::string`, using a pointer as a map key is almost always A Bad Idea.
James McNellis