skfeng
skfeng

Reputation: 669

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!

Upvotes: 2

Views: 124

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

It is more simpler to use the range-based for statement. For example

for ( const std::string &s : a )
{
    for ( char c : s ) std::cout << c;
    std::cout << std::endl;
}

Upvotes: 0

billz
billz

Reputation: 45410

at is a function, need to be called with () not []

update

cout<<a[i].at[j];
//           ^^^

to

a[i].at(j)
//   ^^^^^

To output string, you don't need to cout each char, just do

for (int i=0; i<a.size(); i++)
{
   std::cout << a[i] << "\n";
}
std::cout << std::endl;

Or if C++11:

for(auto const & s : a)
{
   cout << s << "\n";
}

Upvotes: 7

Related Questions