从字符串转换 64 位整数
我正在处理从字符串中读取 64 位无符号整数 unsigned long long
的问题。我的代码应该适用于 GCC 4.3 和 Visual Studio 2010。
我阅读了有关该主题的问题和答案:从文件中读取 64 位整数字符串 并且认为 strtoull
会使工作正常并且比使用 std::stringstream
更有效。遗憾的是,strtoull
在 Visual Studio 的 stdlib.h
中不可用。
所以我写了一个简短的模板函数:
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 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 strtoull
is 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅 http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/d69a6afe-6558-4913-afb0-616f00805229/
顺便说一句,使用 Google 搜索此类内容的方法是注意 Google 会自动认为您错了(就像较新版本的 Visual Studio 一样)并搜索其他内容,因此请务必单击链接搜索您告诉它要搜索的内容。
See http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/d69a6afe-6558-4913-afb0-616f00805229/
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.
当然,您可以轻松地编写自己的函数来处理简单的十进制字符串。标准函数根据数字基数和区域设置处理各种替代方案,这使得它们在任何情况下都很慢。
是的,
stringstream
将在所有这些之上添加堆分配。不,在您能够分辨出差异之前,性能实际上并不重要。有一个更快的选项,使用已弃用的 std::strstream 类,该类不拥有其缓冲区(因此不进行复制或执行分配)。但我不会称其为“更好”。
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.您可以从后面开始一次解析字符串 9 位数字并乘以 1 000 000 000 ^ i,即(最后 8 位数字 * 1)+(接下来的 8 位数字 * 10 亿)...或者
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