How a can I extract these three numbers fast?
I have an std::string
which contains 3 numbers which are separated by spaces
for instance: 123开发者_运维问答334 33335 54544
. How a can I extract these three numbers fast?
int r = ... /* 123334 */
int g = ... /* 33335 */
int b = ... /* 54544*/
The easiest way is to use a stringstream:
std::string numbers = "123334 33335 54544";
std::istringstream parse(numbers);
int r, g, b;
parse >> r;
parse >> g;
parse >> b;
if (!parse)
throw std::runtime_error("invalid string");
Create a stringstream
object, assign to it your string, then use operator>>
to read the 3 numbers.
An alternative solution would be.
std::string numbers = "123334 33335 54544";
std::istringstream iss(numbers);
std::vector<int> int_numbers;
std::transform(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<int> >(int_numbers),
boost::lambda::bind(&boost::lexical_cast<int, std::string>, boost::lambda::_1)
);
But then you need lambda and lexical cast from the boost library.
精彩评论