string A = "test";
double B = 123.45;
float C = 43.23;
char D = 'c';
それらを結合して文字列を生成しようとしていますstring res = "test,123.45,43.23,c"
。最速の方法は何ですか?
ostringstream
良いですが、十分に速くないようです。
string A = "test";
double B = 123.45;
float C = 43.23;
char D = 'c';
それらを結合して文字列を生成しようとしていますstring res = "test,123.45,43.23,c"
。最速の方法は何ですか?
ostringstream
良いですが、十分に速くないようです。
問題は次の 2 つのタスクで構成されます。
2 番目のステップは、std::string::reserve() を使用してメモリを確保することで高速化できます。通常、 std::string は最後に繰り返し追加するときにメモリを数回再割り当てする必要があります。結果の文字列のサイズが事前にわかっている場合、これは回避できます。次に、 std::string::reserve() を使用して std::string にそれについて伝えることができるため、メモリを再割り当てする呼び出しを減らすことができ、長い文字列のパフォーマンスが大幅に向上する可能性があります。
私は最速の方法を知りません。私は単にC++でそれを行う方法を知っています.:)
これは、2 つのアプローチを示すデモ プログラムです。
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string A = "test";
double B = 123.45;
float C = 43.23;
char D = 'c';
std::string res1 = A + ',' + std::to_string( B ) + ',' +
std::to_string( C ) + ',' + D;
std::cout << res1 << std::endl;
std::ostringstream is;
is << A << ',' << B << ',' << C << ',' << D;
std::string res2 = is.str();
std::cout << res2 << std::endl;
return 0;
}
プログラムの出力は
test,123.450000,43.230000,c
test,123.45,43.23,c
だからあなたは好きなものを選ぶことができます.:)
メソッドを高速化するには、メンバー関数を使用して文字列用に十分なメモリを予約する必要がありますreserve
。