通过列表地图迭代?

时间:2012-05-04 14:06:16

标签: c++ list map iterator auto

我有一个map<string, list<int> >,我想在列表上进行迭代并打印出每个数字。我一直在讨论const_iterator和迭代器之间的转换。我做错了什么?

for (map<string, list<int> >::iterator it = words.begin(); it != words.end(); it++)
{
   cout << it->first << ":";
   for (list<int>::iterator lit = it->second.begin(); lit  != it->second.end(); lit++)
      cout << " " << intToStr(*lit);
   cout << "\n";
}

error: conversion from
  ‘std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::list<int, std::allocator<int> > > >’
to non-scalar type
  ‘std::_Rb_tree_iterator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::list<int, std::allocator<int> > > >’
requested|

3 个答案:

答案 0 :(得分:4)

尝试使用新的C ++ 11 auto关键字

for (auto it = words.begin(); it != words.end(); it++)
{
   cout << it->first << ":";
   for (auto lit = it->second.begin(); lit  != it->second.end(); lit++)
      cout << " " << intToStr(*lit);
   cout << "\n";
}

如果仍然出现错误,则定义了不一致的类型。

答案 1 :(得分:3)

map<string, list<int> >::iterator

应该是

map<string, list<int> >::const_iterator

您的mapconst,或者您的地图是class的成员,并且您在const函数中调用此代码,这也使您的map const。无论哪种方式,您都无法在const容器上拥有非const运算符。

编辑:我是唯一一个更喜欢在auto上使用显式类型的人吗?

答案 2 :(得分:3)

尝试使用新的C ++ 11 range-based for loop

for(auto& pair : words) {
  std::cout << pair.first << ":";
  for(auto& i : pair.second) {
    std::cout << " " << intToStr(i);
  }
  std::cout << "\n";
}
相关问题