Transition from string to stringstream to vector <int>

I have this sample program that I want to implement in my application. I want push_back int elements in a string separately, in 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


    }
+5
source share
2 answers
int num;
while (lineStream >> num) numbers.push_back(num);
+12
source

This is a classic example std::back_inserter.

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

You can create a vector from the very beginning if you want

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

Remember to put parentheses around the first argument. The compiler considers this a function declaration differently. If you use a vector to get iterators for numbers, you can directly use istream iterators:

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

All Articles