Question

I'm dealing with the problem of reading a 64bit unsigned integer unsigned long long from a string. My code should work both for GCC 4.3 and Visual Studio 2010.

I read this question and answers on the topic: Read 64 bit integer string from file and thougth that strtoull would make the work just fine and more efficiently than using a std::stringstream. Unfortunately strtoullis not available in Visual Studio's stdlib.h.

So I wrote a short templated function:

template <typename T>
T ToNumber(const std::string& Str)
{
    T Number;
    std::stringstream S(Str);
    S >> Number;
    return Number;
}

unsigned long long N = ToNumber<unsigned long long>("1234567890123456789");

I'm worried about the efficiency of this solution so, is there a better option in this escenario?

Était-ce utile?

La solution

See http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/d69a6afe-6558-4913-afb0-616f00805229/

"It's called _strtoui64(), _wcstoui64() and _tcstoui64(). Plus the _l versions for custom locales.
Hans Passant."

By the way, the way to Google things like this is to notice that Google automatically thinks you're wrong (just like newer versions of Visual Studio) and searches for something else instead, so be sure to click on the link to search for what you told it to search for.

Autres conseils

Of course you can easily enough write your own function to handle simple decimal strings. The standard functions handle various alternatives according to numeric base and locale, which make them slow in any case.

Yes, stringstream will add a heap allocation atop all that. No, performance really doesn't matter until you can tell the difference.

There is a faster option, to use the deprecated std::strstream class which does not own its buffer (hence does not make a copy or perform an allocation). I wouldn't call that "better" though.

You could parse the string 9 digits at a time starting from the rear and multiplying by 1 000 000 000 ^ i, ie (last 8 digits * 1) + (next 8 digits * 1 billion) ... or

(1000000000000000000)+(234567890000000000)+(123456789)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top