C++ 如何推回向量的向量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15484800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:25:22  来源:igfitidea点击:

how to pushback on a vector of vectors?

c++vector

提问by Masterminder

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...

我正在输入 20 行。我想用空格分隔每一行的内容并将其放入向量的向量中。如何制作向量的向量?我很难把它推回去......

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);
    }
}

回答by paddy

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

代码是正确的,但是您的向量中包含零个元素,因此您无法访问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.

你也不需要括号big[i]

回答by juanchopanza

Yo could start with a vector of size ruleNum

你可以从一个大小的向量开始 ruleNum

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

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

这将保存ruleNumvector<string>元素。然后,您可以将元素推回每个元素,就像您目前在发布的示例中所做的那样。

回答by taocp

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);
}

回答by moovon

              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.

要将push_back 推入向量的向量中,我们将push_back 内部向量中的字符串并将内部向量push_back 推入外部向量。

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);