简体   繁体   English

在C ++迭代器问题中使用带有一对的映射作为键

[英]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 我像这样通过for循环将对象插入其中

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. 我在使用find设置迭代器时遇到麻烦。

Suppose I'm using it = pair_map.find(make_pair(string1,string2)) ; 假设我正在使用it = pair_map.find(make_pair(string1,string2)) ;

I've tried declaring pair_map<Key, double>::iterator it; 我试过声明pair_map<Key, double>::iterator it; or map<Key, double>::iterator it; 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 由于typedef的原因,我得到的错误都是长期无效的类型转换错误

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. 在C ++ 11中。

You need 你需要

Map::iterator it = ....

or, in C++11, 或者,在C ++ 11中,

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

pair_map is the name of a variable , not a type . pair_map变量的名称,而不是类型

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

(as juanchopanza says) will work, as will (如juanchopanza所说)将起作用,

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. 如果您有C ++ 11。

Don't use the variable name for the iterator type, but the type name, eg 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. 实际上,您不应该对map typedef,因为这很令人困惑。 Just use the template everywhere. 随处使用模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM