Is it possible to write a one liner in C++ that parses a string containing space…
- User
Is it possible to write a one liner in C++ that parses a string containing space separated numbers into a vector of integers ?
Assistant
Yes, it can be done in one line of C++ as follows:
std::vector<int> v = std::vector<int>(std::istream_iterator<int>(std::istringstream("1 2 3 4 5") >> std::ws), {});This uses:
std::istringstreamto create an input string stream from the string>> std::wsto skip any whitespace while parsingstd::istream_iterator<int>to iterate over the integers in the stream- Constructing a
std::vectorfrom two iterators, beginning and end, to populate the vector with the integers.
So this single line of code parses the space separated string into a vector of integers.
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.