无法使用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: %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)
相关文章:
- 遍历顺序由 std::文件系统directory_iterator给出
- 如何读/写或遍历 std::array 中的特定元素范围?
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 遍历 std::set 中包含的所有三重不同值?
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 如何在重复循环中循环遍历 std::vector
- 为什么 std::set 遍历所有元素的速度较慢?
- 如何遍历 std::variant 的类型?
- 遍历 std::variant 的映射
- 在 std::remove_if 执行期间遍历容器是否安全?
- 遍历 std::string 时如何获取没有数字的字符?
- std::unordered_set迭代器遍历的复杂性
- 使用std :: for_each的树遍历
- 如何使用单 for 循环遍历 std::map<string>int 和 std::vector<int>?
- 遍历std ::映射,效果少于迭代器之间的比较
- 同时遍历两个 std::lists
- 跟踪节点遍历调用 std::map::find
- C ++擦除std::vector.end(),同时循环遍历所有迭代器
- 使用相同的迭代器循环遍历两个 std::vector
- 如何遍历 std::tuple