how to pushback on a vector of vectors?

2019-04-21 00:49发布

问题:

I am taking 20 lines of input. I want to separate the contents of each line by a space and put it into a vector of vectors. How do I make a vector of vectors? I am having have struggles pushing it back...

My input file:

Mary had a little lamb
lalala up the hill
the sun is up

The vector should look like something like this.

ROW 0: {"Mary","had", "a","little","lamb"}
ROW 1: {"lalala","up","the","hill"}

This is my code....

string line; 
vector <vector<string> > big;
string buf;
for (int i = 0; i < 20; i++){
    getline(cin, line);
    stringstream ss(line);

    while (ss >> buf){
        (big[i]).push_back(buf);
    }
}

回答1:

The code is right, but your vector has zero elements in it so you cannot access big[i].

Set the vector size before the loop, either in the constructor or like this:

big.resize(ruleNum);

Alternatively you can push an empty vector in each loop step:

big.push_back( vector<string>() );

You don't need the parentheses around big[i] either.



回答2:

Yo could start with a vector of size ruleNum

vector <vector<string> > big(ruleNum);

This will hold ruleNum empty vector<string> elements. You can then push back elements into each one, as you are currently doing in the example you posted.



回答3:

You can do the following:

string line; 
vector <vector<string> > big;  //BTW:In C++11, you can skip the space between > and >

string currStr;
for (int i = 0; i < ruleNum; i++){
    getline(cin, line);
    stringstream ss(line);
    vector<string> buf;
    while (ss >> currStr){
       buf.push_back(buf);
    }
    big.push_back(buf);
}


回答4:

              vector<vector<string> > v;

to push_back into vectors of vectors, we will push_back strings in the internal vector and push_back the internal vector in to the external vector.

Simple code to show its implementation:

vector<vector<string> > v;
vector<string> s;

s.push_back("Stack");
s.push_back("oveflow");`
s.push_back("c++");
// now push_back the entire vector "s" into "v"
v.push_back(s);


标签: c++ vector