Going from string to stringstream to vector<int>

↘锁芯ラ 提交于 2019-11-28 23:28:02

问题


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?

#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


    }

回答1:


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



回答2:


This is a classic example of 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_iterator<int> begin(lineStream), end;
while(begin != end) cout << *begin++ << " ";


来源:https://stackoverflow.com/questions/455483/going-from-string-to-stringstream-to-vectorint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!