![](/img/trans.png)
[英]What's the correct result of boost::lexical_cast and std::to_string for unsigned char
[英]What's the difference between std::to_string, boost::to_string, and boost::lexical_cast<std::string>?
boost::to_string
(在boost/exception/to_string.hpp
找到)的目的是什么,它與boost::lexical_cast<std::string>
和std::to_string
有何不同?
std::to_string
,自 C++11 起可用,專門用於基本數字類型。 它還有一個std::to_wstring
變體。
它旨在產生與sprintf
相同的結果。
您可以選擇這種形式以避免對外部庫/頭文件的依賴。
throw-on-failure 函數boost::lexical_cast<std::string>
和它的非拋出表親boost::conversion::try_lexical_convert
適用於任何可以插入std::ostream
類型,包括來自其他庫的類型或您自己的代碼。
常見類型存在優化的特化,其通用形式類似於:
template< typename OutType, typename InType >
OutType lexical_cast( const InType & input )
{
// Insert parameter to an iostream
std::stringstream temp_stream;
temp_stream << input;
// Extract output type from the same iostream
OutType output;
temp_stream >> output;
return output;
}
您可以選擇這種形式來利用泛型函數中輸入類型的更大靈活性,或者從您知道不是基本數字類型的類型生成std::string
。
boost::to_string
沒有直接記錄,似乎主要供內部使用。 它的功能表現得像lexical_cast<std::string>
,而不是std::to_string
。
還有更多不同之處:boost::lexical_cast 在將 double 轉換為 string 時的工作方式略有不同。 請考慮以下代碼:
#include <limits>
#include <iostream>
#include "boost/lexical_cast.hpp"
int main()
{
double maxDouble = std::numeric_limits<double>::max();
std::string str(std::to_string(maxDouble));
std::cout << "std::to_string(" << maxDouble << ") == " << str << std::endl;
std::cout << "boost::lexical_cast<std::string>(" << maxDouble << ") == "
<< boost::lexical_cast<std::string>(maxDouble) << std::endl;
return 0;
}
結果
$ ./to_string
std::to_string(1.79769e+308) == 179769313486231570814527423731704356798070600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
boost::lexical_cast<std::string>(1.79769e+308) == 1.7976931348623157e+308
如您所見,boost 版本使用指數表示法 (1.7976931348623157e+308) 而 std::to_string 打印每個數字和六位小數。 對於您的目的,一個可能比另一個更有用。 我個人認為 boost 版本更具可讀性。
這是我為整數到字符串轉換找到的基准,希望它不會對 C++ 中的float 和 double Fast integer to string conversion benchmark產生太大影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.