简体   繁体   English

将一个向量推入另一个向量

[英]Pushing a vector into another vector

I have a file that goes like this: 我有一个像这样的文件:

98
287 2352
987 4313 3253
235 34325 432 123

Basically I want to reproduce this file. 基本上我想重现此文件。 I am trying to import a line at a time, extract the numbers, and push them into vectors. 我正在尝试一次导入一行,提取数字,然后将其推入向量中。 Each vector is pushed into a larger vector. 每个向量被推入更大的向量。

int main(int argc, char* argv[])
{
    int sum = 0, one = 0, two = 1;
    std::string line, number;
    std::vector<int> vec;
    std::vector<std::vector<int>> bigvec;
    auto k = vec.begin();
    std::ifstream in(argv[1]);
    while(in >> line) {
        std::istringstream is(line);
        while(is >> number) {
            vec.push_back(stoi(number));
        }
        bigvec.push_back(vec);
        while(!vec.empty()) {
            vec.pop_back();
        }
        std::cout << std::endl;
    }
    return 0;
}

My code though, when I print the result, seems to put each number in it's own vector instead of reproducing the file. 但是,当我打印结果时,我的代码似乎将每个数字放入其自己的向量中,而不是复制文件。

So my output is 所以我的输出是

98
287
2352
etc.

It seems that the line 看来线

while(is >> number) {
    vec.push_back(stoi(number));
}

pushes one number and then exits the loop. 推一个数字然后退出循环。

Where am I going wrong? 我要去哪里错了?

Your problem lies here: 您的问题出在这里:

while(in >> line)

C++ by defult reads until it encounters interval or new line. C ++由defult读取,直到遇到间隔或换行为止。 In your case it encounters interval before new line. 在您的情况下,它在换行之前遇到间隔。 If you want to take the whole line take: 如果要使用整行,请执行以下操作:

getline(cin, line);

while(in >> line) reads next word from the input. while(in >> line)从输入中读取下一个单词 Use getline(in, line) if you want to read a whole line . 如果要读取整 getline(in, line)请使用getline(in, line)

There are multiple optimizations that you can add to your code. 您可以将多种优化添加到您的代码中。 For instance instead of using stoi on the string you've read you can read an integer from the input stream. 例如,您可以从输入流中读取一个整数,而stoi在已读取的字符串上使用stoi Also instead of popping the vector's elements one by one you can simply call clear . 同样,您不必简单地一个接一个地弹出向量的元素,而只需调用clear

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM