How to reuse ostringstream?
To avoid applications allocating memory frequently, you may want to clear and reuse ostringstream (and its underlying buffer). To reset an object to its initial state, follow these steps:
Using clear and str
In the past, sequences of clear and str were used to achieve this :
<code class="cpp">// 清除,因为 eof 或其他位可能仍然设置。 s.clear(); s.str("");</code>
This works for both input and output stringstreams.
Manually clear and find
Alternatively, you can manually clear and then start with the appropriate sequence lookup:
<code class="cpp">s.clear(); s.seekp(0); // 对于输出:将放置指针指向开头 s.seekg(0); // 对于输入:将获取指针指向开头</code>
This will prevent str Perform some reallocation, instead overwriting whatever is currently in the output buffer. The result is as follows:
<code class="cpp">std::ostringstream s; s << "hello"; s.seekp(0); s << "b"; assert(s.str() == "bello");</code>
For c-functions use std::ends
If you want to use that string for c-functions, you can use std::ends ends, putting a terminating null, like this:
<code class="cpp">std::ostringstream s; s << "hello"; s.seekp(0); s << "b" << std::ends; assert(s.str().size() == 5 && std::strlen(s.str().data()) == 1);</code>
std::ends is a remnant of the deprecated std::strstream, which is able to write directly to what you allocated on the stack char array. You must manually insert a terminating null. However, std::ends is not deprecated, I think because it is still useful in the above situation.
The above is the detailed content of How to Reuse ostringstreams?. For more information, please follow other related articles on the PHP Chinese website!