Using std::istringstream
to parse this out would certainly be more convenient.
But the question being asked is what's going to be most "efficient". And, for better or for worse, #include <iostream>
is not known for its efficiency.
A simple for
loop will be hard to beat, for efficiency's sake.
Assuming that the input doesn't contain any whitespace, only commas and digits:
std::vector<int> split(const std::string &s)
{
std::vector<int> r;
if (!s.empty())
{
int n=0;
for (char c:s)
{
if (c == ',')
{
r.push_back(n);
n=0;
}
else
n=n*10 + (c-'0');
}
r.push_back(n);
}
return r;
}
Feel free to benchmark this again any istream
or istream_iterator
-based approach.