繁体   English   中英

无法使用std :: string作为键在std :: map上进行迭代

[英]Unable to iterate over std::map using a std::string as a key

我的问题几乎与相同,但那里的解决方案尚未解决我的错误。

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> ,但显然我已经包含了。 有什么提示吗?

迭代器在关系上不是可比的,仅是为了相等。 所以说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
}

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

for (iter = receive_times.begin(); iter != eiter; ++iter)

暂无
暂无

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

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