c++ std::to_string实现原理

发布时间 2023-08-14 14:30:07作者: miyanyan

写这篇的起因是看到 MSVC STL 的一个issue,里面提到to_string<int>的实现,正常人的思维是直接除10拿到每位,
其实有个更高效的查表法

字符串转数字

除100拿到两位,并查表填入,少了一半的除法,代价是需要一个201个byte的空间,下面是gcc的实现

// Write an unsigned integer value to the range [first,first+len).
  // The caller is required to provide a buffer of exactly the right size
  // (which can be determined by the __to_chars_len function).
  template<typename _Tp>
    _GLIBCXX23_CONSTEXPR void
    __to_chars_10_impl(char* __first, unsigned __len, _Tp __val) noexcept
    {
#if __cpp_variable_templates
      static_assert(__integer_to_chars_is_unsigned<_Tp>, "implementation bug");
#endif

      constexpr char __digits[201] =
	"0001020304050607080910111213141516171819"
	"2021222324252627282930313233343536373839"
	"4041424344454647484950515253545556575859"
	"6061626364656667686970717273747576777879"
	"8081828384858687888990919293949596979899";
      unsigned __pos = __len - 1;
      while (__val >= 100)
	{
	  auto const __num = (__val % 100) * 2;
	  __val /= 100;
	  __first[__pos] = __digits[__num + 1];
	  __first[__pos - 1] = __digits[__num];
	  __pos -= 2;
	}
      if (__val >= 10)
	{
	  auto const __num = __val * 2;
	  __first[1] = __digits[__num + 1];
	  __first[0] = __digits[__num];
	}
      else
	__first[0] = '0' + __val;
    }