Cla*_*diu 21 c++ boost std tostring lexical-cast
boost::to_string(发现于boost/exception/to_string.hpp)的目的是什么?它boost::lexical_cast<std::string>和它有什么不同std::to_string?
Dre*_*ann 28
std::to_string自C++ 11以来可用,特别适用于基本数字类型.它也有一个std::to_wstring变种.
它旨在产生相同的结果sprintf.
您可以选择此表单以避免依赖外部库/标头.
boost::lexical_cast<std::string>适用于任何可插入的boost::conversion::try_lexical_convert类型,包括其他库中的类型或您自己的代码.
对于常见类型存在优化的特化,通用形式类似于:
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;
}
Run Code Online (Sandbox Code Playgroud)
您可以选择此表单以在通用函数中利用输入类型的更大灵活性,或者std::ostream从您知道不是基本数字类型的类型中生成a .
std::string没有直接记录,似乎主要供内部使用.它的功能表现得像boost::to_string,而不是lexical_cast<std::string>.
还有更多区别:将double转换为string时,boost :: lexical_cast的工作方式有所不同。请考虑以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
结果
$ ./to_string
std::to_string(1.79769e+308) == 179769313486231570814527423731704356798070600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
boost::lexical_cast<std::string>(1.79769e+308) == 1.7976931348623157e+308
Run Code Online (Sandbox Code Playgroud)
如您所见,boost版本使用指数表示法(1.7976931348623157e + 308),而std :: to_string打印每个数字和六个小数位。就您的目的而言,一个可能比另一个有用。我个人认为增强版本更具可读性。
| 归档时间: |
|
| 查看次数: |
7147 次 |
| 最近记录: |