如何循环播放?
我已经尝试过了:
//----- 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> >
并且我试图使用vector作为选项。
答案 0 :(得分:2)
您的迭代代码是正确的;问题是你的输出声明。您的代码正在执行此操作:
std::cout << *it << std::endl;
在这种情况下,*it
引用std::map<string,string>
而std::cout
不知道如何输出地图。也许你想要这样的东西:
std::cout << (*it)["username"] << std::endl;
确保在*it
周围使用()s,否则您将遇到运营商优先问题。
答案 1 :(得分: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';