簡體   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