Rez*_*zie 0 c++ iterator stdmap stdstring
我的问题几乎与这个问题相同,但那里的解决方案还没有解决我的错误.
在main.h
我有:
#include <map>
#include <string>
std::map<std::string, int64_t> receive_times;
Run Code Online (Sandbox Code Playgroud)
并在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);
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试编译时,我收到以下错误:
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)
~~~~ ^ ~~~~~
Run Code Online (Sandbox Code Playgroud)
我在顶部链接的问题中的解决方案是因为缺少了#include <string>
,但显然我已将其包括在内.任何提示?
迭代器不具有相关性,只是为了平等.所以说iter != eiter
.
编写循环的嘈杂方式:
for (std::map<std::string, int64_t>::const_iterator iter = receive_times.begin(),
end = receive_times.end(); iter != end; ++iter)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
(通常最适合typedef
地图类型!)
或者,在C++ 11中:
for (auto it = receive_times.cbegin(), end = receive_timed.cend(); it != end; ++it)
Run Code Online (Sandbox Code Playgroud)
甚至:
for (const auto & p : receive_times)
{
// do something with p.first and p.second
}
Run Code Online (Sandbox Code Playgroud)