user231536
user231536

Reputation: 2711

C++: Elegant way to split string and stuff contents into std::vector

I would like to split a string along whitespaces, and I know that the tokens represent valid integers. I would like to transform the tokens into integers and populate a vector with them.

I could use boost::split, make a vector of token strings, then use std::transform.

What is your solution? Using boost is acceptable.

Upvotes: 11

Views: 3024

Answers (4)

ssube
ssube

Reputation: 48267

Use Boost's string algorithm library to split the string into a vector of strings, then std::for_each and either atoi or boost::lexical_cast to turn them into ints. It's likely to be far simpler than other methods, but may not have the greatest performance due to the copy (if someone has a way to improve it and remove that, please comment).

std::vector<int> numbers;

void append(std::string part)
{
    numbers.push_back(boost::lexical_cast<int>(part));
}

std::string line = "42 4711"; // borrowed from sbi's answer
std::vector<std::string> parts;
split(parts, line, is_any_of(" ,;"));
std::for_each(parts.being(), parts.end(), append);

Roughly.

http://www.boost.org/doc/libs/1_44_0/doc/html/string_algo.html http://www.boost.org/doc/libs/1_44_0/libs/conversion/lexical_cast.htm

Upvotes: 1

sbi
sbi

Reputation: 224079

Something like this:

std::istringstream iss("42 4711 ");
std::vector<int> results( std::istream_iterator<int>(iss)
                        , std::istream_iterator<int>() );

?

Upvotes: 8

theninjagreg
theninjagreg

Reputation: 1756

You could always use strtok or string.find().

Upvotes: 0

James McNellis
James McNellis

Reputation: 355069

You can use Boost.Tokenizer. It can easily be wrapped up into an explode_string function that takes a string and the delimiter and returns a vector of tokens.

Using transform on the returned vector is a good idea for the transformation from strings to ints; you can also just pass the Boost.Tokenizer iterator into the transform algorithm.

Upvotes: 4

Related Questions