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);
}
}
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With