Frage

I have just learned of the "Schlemiel the painter" algorithm (http://en.wikipedia.org/wiki/Joel_Spolsky#Schlemiel_the_Painter.27s_algorithm) and realized I might be Schlemiel.

In my code I do a lot of string concatenation with std::stringstream's operator<<. I was embarrassed to learn that heavy use of c-style concatenation with strcat has a pretty large inefficiency.

Does C++'s std::stringstream's operator<< uses strcat? Or does it use a more efficient method?

War es hilfreich?

Lösung

ostringstream is backed by a stringbuf, which inherits from streambuf; when writing to an ostringstream you are writing to the controlled output sequence of the streambuf. According to 27.6.2:

2 - Each sequence is characterized by three pointers [...]

  • the beginning pointer, or lowest element address in the array [...]
  • the next pointer, or next element address that is a current candidate for reading or writing [...]
  • the end pointer, or first element address beyond the end of the array [...]

So an ostringstream effectively has constant time access to the current end of its output sequence.

Note that using strlen on the output sequence would not work, anyway, as C++ strings are allowed to contain embedded nul characters.

Also note that direct string concatenation (string::operator+=(const string &)) is likely to be more efficient than ostream operators, as there is no requirement to go via virtual methods.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top