簡體   English   中英

std::to_string、boost::to_string 和 boost::lexical_cast 之間有什么區別<std::string> ?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM