[英]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;
}
Hi,when I run the code above,there is an error as below: 嗨,当我运行上面的代码时,会出现如下错误:
error C2109: subscript requires array or pointer type
Please help me and tell me why,thanks! 请帮助我,并告诉我为什么,谢谢!
at
is a function, need to be called with ()
not []
at
是一个函数,需要使用()
而不是[]
来调用
update 更新
cout<<a[i].at[j];
// ^^^
to 至
a[i].at(j)
// ^^^^^
To output string
, you don't need to cout
each char, just do 要输出
string
,您不需要cout
每个char,只需这样做
for (int i=0; i<a.size(); i++)
{
std::cout << a[i] << "\n";
}
std::cout << std::endl;
Or if C++11: 或者如果是C ++ 11:
for(auto const & s : a)
{
cout << s << "\n";
}
It is more simpler to use the range-based for statement. 使用基于范围的for语句更简单。 For example
例如
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.