简体   繁体   English

如何在字符串流的开头插入字符串

[英]How to insert a string to the beginning of a stringstream

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;
}

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. 这依赖于“最重要的const ”来延长临时文件的生存期,并避免制作额外的副本。

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. 这是从这个答案中借用rdbuf方法的,因为这里有趣的问题是如何最小化副本。

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. 它之所以称为流是有原因的。

Assuming ss1 contains "hello" 假设ss1包含“ hello”

ss1 << ss.rdbuf();

or 要么

ss1 << "hello" << ss;

Refer this URL for more info:- 请参考此URL以获取更多信息:-

stringstream 串流

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM