2011-11-26 106 views
0

我的問題與this one幾乎完全相同,但是那裏的解決方案還沒有解決我的錯誤。無法迭代std :: map使用std :: string作爲鍵

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>,但顯然我已包括在內。任何提示?

+5

您不應該在頭文件中定義變量... –

回答

7

迭代器不具有關聯性,僅用於平等。所以說iter != eiter

一個不太吵鬧的方式來編寫循環:(!平時最好typedef地圖類型)

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

或者,在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 
} 
+0

謝謝;這固定它。 – Rezzie

0

容器迭代器的慣用循環結構是:

for (iter = receive_times.begin(); iter != eiter; ++iter) 
相關問題