[英]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.