[英]How to insert a string to the beginning of a stringstream
仅作为示例而非实际代码:
stringstream ss;
ss << " world!";
string hello("Hello");
// insert hello to beginning of ss ??
感谢所有答复,我也找到了下面的代码,该代码可以正常工作:
ostringstream& insert( ostringstream& oss, const string& s )
{
streamsize pos = oss.tellp();
oss.str( s + oss.str() );
oss.seekp( pos + s.length() );
return oss;
}
不复制至少一份就无法做到。 单程:
std::stringstream ss;
ss << " world!";
const std::string &temp = ss.str();
ss.seekp(0);
ss << "Hello";
ss << temp;
这依赖于“最重要的const
”来延长临时文件的生存期,并避免制作额外的副本。
或者,更简单甚至更快:
std::stringstream ss;
ss << " world!";
std::stringstream temp;
temp << "Hello";
temp << ss.rdbuf();
ss = std::move(temp); // or ss.swap(temp);
这是从这个答案中借用rdbuf
方法的,因为这里有趣的问题是如何最小化副本。
我看到的唯一方法是从流中创建字符串并为其他字符串添加前缀
string result = hello + ss.str();
它之所以称为流是有原因的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.