Going from string to stringstream to vector<int>
Asked Answered
D

3

12

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


    }
Dormeuse answered 18/1, 2009 at 17:11 Comment(0)
L
19
int num;
while (lineStream >> num) numbers.push_back(num);
Lester answered 18/1, 2009 at 17:14 Comment(0)
I
35

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++ << " ";
Improper answered 18/1, 2009 at 17:22 Comment(4)
This is a perfect example, imho, of whats wrong with C++. In virtually every other language, this would be a split on ' ', followed by something like .toInt() for each element. Instead, we have an immensely complicated collection of templatized algorithms being applied.Saum
I hear what you're saying dicroce. OTOH, this more complicated approach is faster, since you avoid creating a temporary array or list of strings, and also more powerful -- much the same code could be used to copy any sort of "range of values" (represented by a pair of iterators) into a vector.Sludgy
C++11: vector<int> numbers(istream_iterator<int>(lineStream), {});Coffee
@KerrekSB yours is the first non-theoretic example I have seen for passing an initializer list to a deduced template parameter. NiceImproper
L
19
int num;
while (lineStream >> num) numbers.push_back(num);
Lester answered 18/1, 2009 at 17:14 Comment(0)
Y
0
string token;
char del = " ";
istringstream iss(line);   
while(getline(iss,token,del)) v1.push_back(stoi(token));
Yulandayule answered 6/5 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.