2015-02-12 266 views
0

如何循環這個?C++循環std :: vector <std :: map <std :: string,std :: string>>

我已經嘗試過:

//----- code 
std::vector<std::map<std::string, std::string> >::iterator it; 
for (it = users.begin(); it != users.end(); it++) { 
    std::cout << *it << std::endl; // this is the only part i changed according to the codes below 
} 
//----- error 
error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::map<std::basic_string<char>, std::basic_string<char> >]’ 

//----- code 
std::cout << *it["username"] << std::endl; 
//----- error 
note: template argument deduction/substitution failed: 
note: ‘std::map<std::basic_string<char>, std::basic_string<char> >’ is not derived from ‘const std::complex<_Tp>’ 
//----- code 
std::cout << *it->second << std::endl; // also tried with parenthesis - second() 
//----- error 
error: ‘class std::map<std::basic_string<char>, std::basic_string<char> >’ has no member named ‘second’ 
//----- code 
for(const auto& curr : it) std::cout << curr.first() << " = " << curr.second() << std::endl; 
//----- error 
error: unable to deduce ‘const auto&’ from ‘<expression error>’ 

,最後

//----- code 
std::map<std::string, std::string>::iterator curr, end; 
for(curr = it.begin(), end = it.end(); curr != end; ++curr) { 
    std::cout << curr->first << " = " << curr->second << std::endl; 
} 
//----- error 
‘std::vector<std::map<std::basic_string<char>, std::basic_string<char> > >::iterator’ has no member named ‘begin‘ & ‘end’ 

我希望我給出一個明確的細節..然後上面是下面的代碼是錯誤..而目前我的腦子一片空白。

和抱歉這個..

我已經讓這種類型的工作:std::map<int, std::map<std::string, std::string> >和IM嘗試使用向量作爲一個選項。

回答

2

您的迭代代碼是正確的;問題是你的輸出語句。您的代碼是這樣做的:

std::cout << *it << std::endl; 

在這種情況下,*itstd::map<string,string>std::cout不知道如何輸出的地圖。也許你想是這樣的:

std::cout << (*it)["username"] << std::endl; 

確保使用()s左右*it否則,你將有運算符優先級的問題。

2
std::vector<std::map<std::string, std::string> >::iterator it; 
for (it = users.begin(); it != users.end(); it++) { 
    std::cout << *it << std::endl; 

users.empty(),上面<<運營商嘗試串流一個std::map<std::string, std::string>對象,但標準庫不提供過載流映射:如何將它知道你按鍵之間想要的分隔符價值觀和元素之間?

我建議你打破下來的問題是這樣的:

std::vector<std::map<std::string, std::string> >::iterator it; 
for (it = users.begin(); it != users.end(); it++) 
{ 
    std::map<std::string, std::string>& m = *it; 

    for (std::map<std::string, std::string>::iterator mit = m.begin(); 
     mit != m.end(); ++mit) 
     std::cout << mit->first << '=' << mit->second << '\n'; 

    std::cout << "again, username is " << m["username"] << '\n'; 
} 

這可以簡化在C++ 11:

for (auto& m : users) 
    for (auto& kv : m) 
     std::cout << kv.first << '=' << kv.second << '\n'; 
+0

THANK YOU VERY MUCH ...我想你所有的答案,這一切工作.. – xeroblast 2015-02-12 06:28:29

相關問題