C++ 从字符串到字符串流再到 vector<int>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/455483/
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 15:26:29  来源:igfitidea点击:

Going from string to stringstream to vector<int>

c++stringvectorstringstream

提问by andandandand

I've this sample program of a step that I want to implement on my application. I want to push_back the int elements on the string separately, into a vector. How can I?

我有一个我想在我的应用程序上实现的步骤的示例程序。我想将字符串上的 int 元素分别推回一个向量中。我怎样才能?

#include <iostream>
#include <sstream>

#include <vector>

using namespace std;

int main(){

    string line = "1 2 3 4 5"; //includes spaces
    stringstream lineStream(line);


    vector<int> numbers; // how do I push_back the numbers (separately) here?
    // in this example I know the size of my string but in my application I won't


    }

回答by Johannes Schaub - litb

This is a classic example of std::back_inserter.

这是一个经典的例子std::back_inserter

copy(istream_iterator<int>(lineStream), istream_iterator<int>(),
     back_inserter(numbers));

You can create the vector right from the start on, if you wish

如果您愿意,您可以从一开始就创建矢量

vector<int> numbers((istream_iterator<int>(lineStream)), 
                    istream_iterator<int>());

Remember to put parentheses around the first argument. The compiler thinks it's a function declaration otherwise. If you use the vector for just getting iterators for the numbers, you can use the istream iterators directly:

请记住在第一个参数周围加上括号。否则编译器认为它是一个函数声明。如果您使用向量来获取数字的迭代器,则可以直接使用 istream 迭代器:

istream_iterator<int> begin(lineStream), end;
while(begin != end) cout << *begin++ << " ";

回答by Mehrdad Afshari

int num;
while (lineStream >> num) numbers.push_back(num);