2

int から string への変換に関する非常に多くの投稿がありますが、それらはすべて、画面への出力または ostringstream の使用のいずれかを実際に伴います。

私は ostringstream を使用していましたが、ランタイムがひどいため、私の会社はストリームを使用することを望んでいません。

私はこれをC++ファイルで行っていました。

私の問題は、実行中に何百万ものストリームを作成し、バッファに書き込み、コンテンツを文字列にコピーしようとしていたことです。

ostringstream OS;
os << "TROLOLOLOLOL";
std::string myStr = os.str();

このバッファを作成してから全体にコピーするため、冗長性があります。うーん!

4

4 に答える 4

6

C++11 の場合:

string s = std::to_string(42);

数週間前にベンチマークを行い、それらの結果を得ました (現在の Xcode に同梱されている clang と libc++ を使用):

stringstream took 446ms
to_string took 203ms
c style took 170ms

次のコードを使用します。

#include <iostream>
#include <chrono>
#include <sstream>
#include <stdlib.h>

using namespace std;

struct Measure {
  chrono::time_point<chrono::system_clock> _start;
  string _name;

  Measure(const string& name) : _name(name) {
    _start = chrono::system_clock::now();
  }

  ~Measure() {
    cout << _name << " took " << chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now() - _start).count() << "ms" << endl;
  }
};



int main(int argc, const char * argv[]) {
  int n = 1000000;
  {
    Measure m("stringstream");
    for (int i = 0; i < n; ++i) {
      stringstream ss;
      ss << i;
      string s = ss.str();
    }
  }
  {
    Measure m("to_string");
    for (int i = 0; i < n; ++i) {
      string s = to_string(i);
    }
  }
  {
    Measure m("c style");
    for (int i = 0; i < n; ++i) {
      char buff[50];
      snprintf(buff, 49, "%d", i);
      string s(buff);
    }
  }
  return 0;
}
于 2012-11-13T17:31:07.120 に答える
3

C++11 では、std::to_string. おそらくstringstreamフードの下でテクニックを使用していますが。

于 2012-11-13T17:30:59.487 に答える
0

次のパフォーマンスチャートを確認する必要がありますboost::lexical_cast

http://www.boost.org/doc/libs/1_52_0/doc/html/boost_lexical_cast/performance.html

lexical_castをstringstream(構築ありとなし)およびscanf/printfと比較します。

ほとんどの場合、boost :: lexical_castはscanf、printf、std::stringstreamよりも高速です。

于 2012-11-13T17:39:58.943 に答える
0

stringstream バッファの再利用。これはスレッドセーフではないことに注意してください。

#include <sstream>
#include <iostream>
#include <string>

template<class T>
bool str_to_type(const char *str, T &value) {
  static std::stringstream strm;
  if ( str ) {
    strm << std::ends;
    strm.clear();
    strm.setf(std::ios::boolalpha);
    strm.seekp(0);
    strm.seekg(0);
    strm << str << std::ends;
    strm >> value;
    return !strm.fail();
  }
  return false;
}

int main(int argc, char *argv[])
{
  int i;
  if (!str_to_type("42", i))
    std::cout << "Error" << std::endl;
  std::cout << i << std::endl;
    return 0;
}
于 2012-11-13T18:13:39.377 に答える