stringstream用法

来源:互联网 发布:我知女人心南宫寒版 编辑:程序博客网 时间:2024/06/10 06:13

stringstream是个好东西,网上有不少文章,讨论如何用它实现各种数据类型的转换(比如把double或int转换为string类型)。但如 果stringstream使用不当,当心内存出问题(我就吃过亏^_^)。
注意重复使用同一个stringstream对象时要 先继续清空,而清空很容易想到是clear方法,而在stringstream中这个方法实际上是清空stringstream的状态(比如出错等),真 正清空内容需要使用.str(“”)方法
试试下面的代码,运行程序前打开任务管理器,过不了几十秒,所有的内存都将被耗尽!

#include <cstdlib>#include <iostream>#include <sstream>using namespace std;/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////int main(int argc, char * argv[]){   std::stringstream stream;   string str;while(1){        //clear(),这个名字让很多人想当然地认为它会清除流的内容。    //实际上,它并不清空任何内容,它只是重置了流的状态标志而已!    stream.clear();        // 去掉下面这行注释,清空stringstream的缓冲,每次循环内存消耗将不再增加!     //stream.str("");           stream<<"sdfsdfdsfsadfsdafsdfsdgsdgsdgsadgdsgsdagasdgsdagsadgsdgsgdsagsadgs ";    stream>>str;          // 去掉下面两行注释,看看每次循环,你的内存消耗增加了多少!      //cout<<"Size of stream = "<<stream.str().length()<<endl;      //system("PAUSE");}system("PAUSE ");return EXIT_SUCCESS;}
把stream.str("");    那一行的注释去掉,再运行程序,内存就正常了看来stringstream似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消 耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )。另外不要企图用 stream.str().resize(0),或 stream.str().clear() 来清除缓冲,使用它们似乎可以让stringstream的内存消耗不要增长得那么快,但仍然不能达到清除stringstream缓冲的效果(不信做个 实验就知道了,内存的消耗还在缓慢的增长!)

关于erease()函数的用法:
erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)
下面给一个例子:

int main (){  string str ("This is an example phrase.");  string::iterator it;  // 第(1)种用法  str.erase (10,8);  cout << str << endl;        // "This is an phrase."  // 第(2)种用法  it=str.begin()+9;  str.erase (it);  cout << str << endl;        // "This is a phrase."  // 第(3)种用法  str.erase (str.begin()+5, str.end()-7);  cout << str << endl;        // "This phrase."  return 0;}
转载:http://blog.csdn.net/chjp2046/article/details/5460462www.cnblogs.com/ylwn817/articles/1967689.html
原创粉丝点击