[英]c++: Iteration of vector<string>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> a;
a.push_back("1 1 2 4");
a.push_back("2 3 3 3");
a.push_back("2 2 3 5");
a.push_back("3 3 3 3");
a.push_back("1 2 3 4");
for (int i=0;i<a.size();i++)
for(int j=0;j<a[i].length();j++)
cout<<a[i].at[j];
return 0;
}
嗨,當我運行上面的代碼時,會出現如下錯誤:
error C2109: subscript requires array or pointer type
請幫助我,並告訴我為什么,謝謝!
at
是一個函數,需要使用()
而不是[]
來調用
更新
cout<<a[i].at[j];
// ^^^
至
a[i].at(j)
// ^^^^^
要輸出string
,您不需要cout
每個char,只需這樣做
for (int i=0; i<a.size(); i++)
{
std::cout << a[i] << "\n";
}
std::cout << std::endl;
或者如果是C ++ 11:
for(auto const & s : a)
{
cout << s << "\n";
}
使用基於范圍的for語句更簡單。 例如
for ( const std::string &s : a )
{
for ( char c : s ) std::cout << c;
std::cout << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.