pyCthon
pyCthon

Reputation: 12341

using map with a pair as a key in c++ iterator issues

I have a pair and a map declared as such

typedef pair<string,string> Key;
typedef map< Key, double> Map;

i insert objects into them via a for loop as such

Key p (string1, string2 );
pair_map.insert(make_pair( p, double1 ) );

how can i find elements in the map? I am having trouble setting up the iterator with find.

Suppose I'm using it = pair_map.find(make_pair(string1,string2));

I've tried declaring pair_map<Key, double>::iterator it; or map<Key, double>::iterator it; but neither are working for me. How can i fix this?

the errors i get are all long invalid cast errors because of the typedef's

Upvotes: 1

Views: 194

Answers (4)

ForEveR
ForEveR

Reputation: 55887

Map::iterator it = pair_map.find(make_pair(string1, string2));

And of course you can use

auto it = ...;

or

decltype(pair_map.begin()) it = ...;

in C++11.

Upvotes: 6

Useless
Useless

Reputation: 67723

pair_map is the name of a variable, not a type.

Map::iterator it = pair_map.find(make_pair(string1,string2));

(as juanchopanza says) will work, as will

std::map<Key, double>::iterator it = pair_map.find(make_pair(string1,string2));

or

auto it = pair_map.find(make_pair(string1,string2));

if you have C++11.

Upvotes: 2

slaphappy
slaphappy

Reputation: 6999

Don't use the variable name for the iterator type, but the type name, e.g. instead of :

pair_map<Key, double>::iterator it;

Use

Map::iterator it;

Or

map<Key, double>::iterator it;

Actually, you shouldn't typedef you map, since it's confusing. Just use the template everywhere.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227390

You need

Map::iterator it = ....

or, in C++11,

auto it = pair_map.find(make_pair(string1, string2));

Upvotes: 4

Related Questions