简体   繁体   English

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

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

My question is almost identical to this one , but the solution there hasn't resolved my error. 我的问题几乎与相同,但那里的解决方案尚未解决我的错误。

In main.h I have: main.h我有:

#include <map>
#include <string>

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

And in main.cpp : 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);

However, when I try and compile I get the following error: 但是,当我尝试编译时,出现以下错误:

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)
                                     ~~~~ ^ ~~~~~

The solution in the question I linked to at the top is because there was a missing #include <string> , but obviously I have that included. 我在顶部链接到的问题的解决方案是因为缺少#include <string> ,但显然我已经包含了。 Any hints? 有什么提示吗?

Iterators are not relationally comparable, only for equality. 迭代器在关系上不是可比的,仅是为了相等。 So say iter != eiter . 所以说iter != eiter

A less noisy way to write the loop: 编写循环的一种较不吵杂的方法:

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

(Usually best to typedef the map type!) (通常最好对地图类型进行typedef !)

Or, in C++11: 或者,在C ++ 11中:

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

Or even: 甚至:

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