Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string of integers into a vector full of int's?

Tags:

c++

vector

I know other questions have been asked about this same thing, however, I have used those other resources to come up with what I have now and I am getting an error that I can't seem to figure out. Also, keep in mind that I am a c++ beginner. That being said, I have a very large string filled with integers formatted as follows: newString = "12 -34 50 2 -102 13 78 9" (the actual string is much larger). I then try to create a function using transform() to convert the string into a vector of int's:

int convertString(){

    istringstream is(newString);
    vector<int> intVector;
    transform(istream_iterator<string>( is ),
              istream_iterator<string>(),
              back_inserter( intVector ),
              []( const string &newString ){ return ( stoi( newString ) ); } );//This is the line indicated in the error!
    for(int x : intVector )
        cout << x << ' '<<endl;

    return 0;
    }

The error that I am getting is That there is an expected expression at the indicated error line... Any ideas how to fix this?

Thanks in advance and just let me know if anything is unclear!

like image 941
user3798269 Avatar asked Mar 17 '23 09:03

user3798269


1 Answers

Assuming you're reasonably certain the input contains only properly formatted ints, (or can live with just stopping reading when/if something other than a readable integer is encountered) there's no need for transform here--the istream_iterator itself can handle the conversion perfectly well. You can initialize the vector directly from the iterators, giving code like this:

std::istringstream is(newString);
std::vector<int> intVector { std::istream_iterator<int>(is), 
                             std::istream_iterator<int>()};

This would differ from your version in one respect: if you give a string to stoi that it can't convert to an integer, it'll throw an exception--invalid_argument if it contains something like ac; that can't convert to an integer at all, or out_of_range if it contains something like 50 digits, that produce a result that won't fit in the target type.

like image 193
Jerry Coffin Avatar answered Apr 26 '23 22:04

Jerry Coffin