What is the most effective way to transform a string of integers, eg. (1,5,73,2) in an array of integers?

advertisements

I have had a similar problem while coding in Java, and in that instance, I used str1.split(",") to change the string of integers into an array of them.

Is there a method in C++ that has a similar function to Java's split method, or is the best way using a for loop to achieve the same goals?


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.