use*_*967 77 c++ string stringstream
如何将字符串流的状态"重置"为创建它时的状态?
int firstValue = 1;
int secondValue = 2;
std::wstringstream ss;
ss << "Hello: " << firstValue;
std::wstring firstText(ss.str());
//print the value of firstText here
//How do I "reset" the stringstream here?
//I would like it behave as if I had created
// stringstream ss2 and used it below.
ss << "Bye: " << secondValue;
std::wstring secondText(ss.str());
//print the value of secondText here
Run Code Online (Sandbox Code Playgroud)
Dar*_*ner 127
这是我通常这样做的方式:
ss.str("");
ss.clear(); // Clear state flags.
Run Code Online (Sandbox Code Playgroud)
基于上面的答案,我们还需要重置所有格式。总之,当构造新的 std::stringstream 实例时,我们将缓冲区内容、流状态标志和任何格式重置为其默认值。
void reset(std::stringstream& stream)
{
const static std::stringstream initial;
stream.str(std::string());
stream.clear();
stream.copyfmt(initial);
}
Run Code Online (Sandbox Code Playgroud)
我会做
std::wstringstream temp;
ss.swap(temp);
Run Code Online (Sandbox Code Playgroud)
编辑:修复了christianparpart和Nemo报告的错误.谢谢.
PS:上面的代码在堆栈上创建了一个新的stringstream对象,并将所有内容ss与新对象中的内容进行交换.
好处:
ss现在将处于一个新的状态.ss内部数据重置为初始状态.更多:
与赋值运算符相比:在新对象在堆中具有分配的缓冲区的情况下,STL交换方法可以比赋值运算符更快.在这种情况下,赋值运算符必须为新对象分配缓冲区,然后它可能需要为旧对象分配另一个缓冲区,然后将数据从新对象的缓冲区复制到旧对象的新缓冲区.实现快速交换非常容易,例如,它只是交换缓冲区的指针.
C++ 11.我已经看到了一些比swap更慢的移动赋值运算符的实现,尽管可以修复,但是STL开发人员可能不希望留下带有大量数据的移动对象
std::move()不保证移动的对象被清空.return std::move(m_container);不清楚m_container.所以你必须这样做
auto to_return(std :: move(m_container)); m_container.clear(); 回归...
哪个不能比
auto to_return;
m_container.swap(to_return);
return to_return;
Run Code Online (Sandbox Code Playgroud)
因为后者保证它不会复制缓冲区.
所以我总是喜欢swap()它,只要它适合.
| 归档时间: |
|
| 查看次数: |
52541 次 |
| 最近记录: |