无法使用std::string作为键遍历std::map

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

本文关键字:std 遍历 map string      更新时间:2023-10-16

我的问题几乎与这个相同,但解决方案并没有解决我的错误。

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: %ldn", 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)