24

boost::to_string(在 中找到)的目的是什么boost/exception/to_string.hpp,它与boost::lexical_cast<std::string>和有何不同std::to_string

4

3 回答 3

31

std::to_string,自 C++11 起可用,专门用于基本数字类型。它也有一个std::to_wstring变种。

它旨在产生相同的结果sprintf

您可以选择这种形式来避免对外部库/头文件的依赖。


throw-on-failure 函数boost::lexical_cast<std::string>及其非抛出表亲boost::conversion::try_lexical_convert适用于任何可以插入到 astd::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从您知道不是基本数字类型的类型中生成 a。


boost::to_string没有直接记录,似乎主要供内部使用。它的功能表现得像lexical_cast<std::string>,不是std::to_string

于 2015-04-01T19:44:40.227 回答
8

还有更多区别: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;
}

结果

$ ./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 版本更具可读性。

于 2017-01-17T13:33:14.840 回答
-2

这是我发现的整数到字符串转换的基准,希望它不会对 float 和 double Fast integer to string conversion benchmark in C++改变太大。

于 2020-09-01T19:16:59.490 回答