c++ - 整数到字符串优化函数?

标签 c++ string optimization c++11 integer

我目前有这个函数可以将无符号整数转换为字符串(我需要一个适用于非标准类型的函数,如 __uint128_t):

#include <iostream>
#include <algorithm>
#include <string>

template <typename UnsignedIntegral>
std::string stringify(UnsignedIntegral number, const unsigned int base)
{
    static const char zero = '0';
    static const char alpha = 'A';
    static const char ten = 10;
    std::string result;
    char remainder = 0;
    do {
        remainder = number%base;
        result += (remainder < ten) ? (zero+remainder) : (alpha+remainder-ten);
        number /= base;
    } while (number > 0);
    std::reverse(std::begin(result), std::end(result));
    return result;
}

int main()
{
   std::cout<<stringify(126349823, 2)<<std::endl;
   return 0;
}

有什么办法可以优化这段代码吗?

最佳答案

您可能想阅读 Alexei Alexandrescu 的这篇文章,他在文中以使用(固定基数)int 到字符串的转换为例讨论了低级优化:

https://www.facebook.com/notes/facebook-engineering/three-optimization-tips-for-c/10151361643253920

请记住,优化时最重要的事情始终是分析。

关于c++ - 整数到字符串优化函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22202058/

相关文章:

linux - Bash编程如何调用 "$i+1"

c - C 中 const 关键字的歧义

c - 优化 sqrt(n) - sqrt(n-1)

c++ - 如何在拒绝 float 和空格的同时接受整数输入?

c++ - 在类中分配函数指针会在 C++ 中给出值类型错误

python - 计算文件中数字字符串的总和,而数字位于随机行中

mysql - 如何在 MYSQL 中优化此查询?

c++ - 比较是否意味着分支?

c++ - 从命令行向 C++ 传递参数

C++:编译器仅按需实例化模板函数?