2 Mayıs 2019 Perşembe

std::to_chars metodu

Giriş
Şu satırı dahil ederiz.
#include <charconv>
C++17 ile geliyor. Sayıyı string'e çevirir. Bu metodun tersini std::from_chars() yapar. Açıklaması şöyle.
Before C++17, there existed a variety of methods to convert integers, floats, and doubles to and from strings. For example,  std::stringstream, std::to_string, std::atoi, std::stoi, and others could have been used to accomplish these tasks.
Yukarıdaki diğer yöntemlere göre daha hızlı olduğu söyleniyor. Açıklaması şöyle.
std::stringstream is the heavyweight champion. It takes into consideration things like the the stream's imbued locale, and its functionality involves things like constructing a sentry object for the duration of the formatted operation, in order to deal with exception-related issues. Formatted input and output operations in the C++ libraries have some reputation for being heavyweight, and slow.

std::to_string is less intensive than std::istringstream but it still returns a std::string, whose construction likely involves dynamic allocation (less likely with modern short string optimization techniques, but still likely). And, in most cases the compiler still needs to generate all the verbiage, at the call site, to support a std::string object, including its destructor.

std::to_chars are designed to have as little footprint as possible. You provide the buffer, and std::to_chars does very little beyond actually formatting the numeric value into the buffer, in a specific format, without any locale-specific considerations, with the only overhead of making sure that the buffer is big enough. Code that uses std::to_chars does not need to do any dynamic allocation.

std::to_chars is also a bit more flexible in terms of formatting options, especially with floating point values. std::to_string has no formatting options.

std::from_chars is, similarly, a lightweight parser, that does not need to do any dynamic allocation, and does not need to sacrifice any electrons to deal with locale issues, or overhead of stream operations.
Örnek
Şöyle yaparız.
std::array<char, 10> str{};
std::to_chars(str.data(), str.data()+str.size(), 42);
std::cout << str.data();

Hiç yorum yok:

Yorum Gönder