仅作为示例而非实际代码:
stringstream ss;
ss << " world!";
string hello("Hello");
// insert hello to beginning of ss ??
Run Code Online (Sandbox Code Playgroud)
感谢所有答复,我也找到了下面的代码,该代码可以正常工作:
ostringstream& insert( ostringstream& oss, const string& s )
{
streamsize pos = oss.tellp();
oss.str( s + oss.str() );
oss.seekp( pos + s.length() );
return oss;
}
Run Code Online (Sandbox Code Playgroud)
不复制至少一份就无法做到。单程:
std::stringstream ss;
ss << " world!";
const std::string &temp = ss.str();
ss.seekp(0);
ss << "Hello";
ss << temp;
Run Code Online (Sandbox Code Playgroud)
这依靠“最重要的const”来延长临时文件的寿命并避免制作额外的副本。
或者,更简单甚至更快:
std::stringstream ss;
ss << " world!";
std::stringstream temp;
temp << "Hello";
temp << ss.rdbuf();
ss = std::move(temp); // or ss.swap(temp);
Run Code Online (Sandbox Code Playgroud)
这是rdbuf从该答案中借用的方法,因为这里有趣的问题是如何最小化副本。
我能看到的唯一方法是从流创建字符串并为其他字符串添加前缀
string result = hello + ss.str();
Run Code Online (Sandbox Code Playgroud)
它被称为流是有原因的。