[英]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. 我可以使用boost :: split,创建一个令牌字符串的向量,然后使用std :: transform。
What is your solution? 你的解决方案是什么? Using boost is acceptable.
使用boost是可以接受的。
Something like this: 像这样的东西:
std::istringstream iss("42 4711 ");
std::vector<int> results( std::istream_iterator<int>(iss)
, std::istream_iterator<int>() );
? ?
You can use Boost.Tokenizer . 您可以使用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. 它可以很容易地被包装到一个
explode_string
函数中,该函数接受一个字符串和分隔符并返回一个标记向量。
Using transform
on the returned vector is a good idea for the transformation from strings to ints; 对返回的向量使用
transform
是从字符串到int的转换的一个好主意; you can also just pass the Boost.Tokenizer iterator into the transform
algorithm. 您也可以将Boost.Tokenizer迭代器传递给
transform
算法。
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 int
s. 使用Boost的字符串算法库将字符串
split
为字符串向量,然后使用std::for_each
和atoi
或boost::lexical_cast
将它们转换为int
。 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 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
你总是可以使用strtok或string.find()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.