Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pushback on a vector of vectors?

Tags:

c++

vector

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);
    }
}
like image 899
Masterminder Avatar asked Mar 18 '13 19:03

Masterminder


2 Answers

              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);
like image 97
moovon Avatar answered Sep 21 '22 11:09

moovon


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.

like image 20
paddy Avatar answered Sep 22 '22 11:09

paddy