无法使用std :: string作为键迭代std :: map

时间:2011-11-26 13:32:57

标签: c++ iterator stdstring stdmap

我的问题几乎与this one相同,但那里的解决方案并没有解决我的错误。

main.h我有:

#include <map>
#include <string>

std::map<std::string, int64_t> receive_times;

main.cpp

std::map<std::string, int64_t>::const_iterator iter;
std::map<std::string, int64_t>::const_iterator eiter = receive_times.end();

for (iter = receive_times.begin(); iter < eiter; ++iter)
  printf("%s: %ld\n", iter->first.c_str(), iter->second);

然而,当我尝试编译时,我收到以下错误:

error: invalid operands to binary expression ('std::map<std::string, int64_t>::const_iterator' (aka '_Rb_tree_const_iterator<value_type>') and 'std::map<std::string, int64_t>::const_iterator'
  (aka '_Rb_tree_const_iterator<value_type>'))
  for (iter = receive_times.begin(); iter < eiter; ++iter)
                                     ~~~~ ^ ~~~~~

我在顶部链接的问题中的解决方案是因为缺少#include <string>,但显然我已将其包括在内。任何提示?

2 个答案:

答案 0 :(得分:7)

迭代器在关系上没有可比性,只是为了平等。所以说iter != eiter

编写循环的嘈杂方式:

for (std::map<std::string, int64_t>::const_iterator iter = receive_times.begin(),
     end = receive_times.end(); iter != end; ++iter)
{
  // ...
}

(通常最适合typedef地图类型!)

或者,在C ++ 11中:

for (auto it = receive_times.cbegin(), end = receive_timed.cend(); it != end; ++it)

甚至:

for (const auto & p : receive_times)
{
  // do something with p.first and p.second
}

答案 1 :(得分:0)

容器迭代器的惯用循环结构是:

for (iter = receive_times.begin(); iter != eiter; ++iter)
相关问题