例如我有一张这样的地图:
map<string , map <int , int>> example;
Run Code Online (Sandbox Code Playgroud)
和一个迭代器:
map<string , map <int, int>>::iterator iter;
string word;
Run Code Online (Sandbox Code Playgroud)
我想访问内部地图:
for(iter = example.begin();iter!=example.end;iter++){
iter = Map.find(word);
iter -> second //
}
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能访问内部地图,例如如果 iter->second ==4 - 它不正确,或者我可以做 (iter->second)->second 吗?你能给我一个建议吗?我不明白迭代器给了我一对 (int,int) 所以我试着做另一个迭代器映射 ::iterator i; 和 assing iter->second = i,但它没有帮助我;
对于复杂类型,使用typedef
它会让你的生活更轻松:
typedef std::map< int, int > Ints;
typedef std::map< std::string, Ints > String2Ints;
String2Ints example;
std::string word;
String2Ints::iterator it = example.find( word );
if( it != example.end() ) {
Ints &innerMap = it->second;
Ints::iterator innerit = innerMap.find( 4 );
if( innerit != innerMap.end() )
std::cout << "found value for word " << word << " 4 - " << innerit->second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
此外,您的循环和 find inside 不正确,您应该遍历 map 或搜索 value by find()
,您在代码中所做的事情没有任何意义(如果找到单词,技术上是无限循环)