7

For example only and not the actual code:

stringstream ss;
ss << " world!";

string hello("Hello");

// insert hello to beginning of ss ??

Thanks for all the responses, I also found this code, which works:

ostringstream& insert( ostringstream& oss, const string& s )
{
  streamsize pos = oss.tellp();
  oss.str( s + oss.str() );
  oss.seekp( pos + s.length() );
  return oss;
}
dlsou
  • 635
  • 2
  • 8
  • 18

3 Answers3

9

You cannot do it without making at least one copy. One way:

std::stringstream ss;
ss << " world!";

const std::string &temp = ss.str();
ss.seekp(0);
ss << "Hello";
ss << temp;

This relies on the "most important const" to extend the lifetime of the temporary and avoid making an extra copy.

Or, simpler and possibly faster:

std::stringstream ss;
ss << " world!";

std::stringstream temp;
temp << "Hello";
temp << ss.rdbuf();
ss = std::move(temp); // or ss.swap(temp);

This borrows the rdbuf approach from this answer, since the interesting problem here is how to minimize copies.

Nemo
  • 70,042
  • 10
  • 116
  • 153
  • So it does, my bad. – Nic Nov 25 '18 at 05:49
  • @NicHartley: No problem, but would you mind removing your downvote? :) – Nemo Nov 25 '18 at 05:50
  • Votes are locked in after 15 minutes, so unfortunately I can't. The `seekp` thing solved my problem; I'd upvote this if I could. – Nic Nov 25 '18 at 05:55
  • 1
    @NicHartley: Ah. No worries. I believe the `seekp` approach copies more data around, even with C++11 move semantics. Come to think of it, the simplest and fastest approach is probably just to create a new `stringstream` and `swap` (or `std::move`) the guts. I went ahead and edited my answer, which also should allow you to change your vote. – Nemo Nov 25 '18 at 06:16
2

the only way i can see is to create the string from stream and prefix your other string

string result = hello + ss.str();

its called a stream for a reason.

AndersK
  • 35,813
  • 6
  • 60
  • 86
1

Assuming ss1 contains "hello"

ss1 << ss.rdbuf();

or

ss1 << "hello" << ss;

Refer this URL for more info:-

stringstream

Siva Charan
  • 17,940
  • 9
  • 60
  • 95