zoukankan      html  css  js  c++  java
  • 字符串流sstream[part2/使用同一个字符串流反复读写数据]

      stringstream构造函数会特别消耗内存,似乎不打算主动释放内存(或许是为了提高效率),如果你要在程序中使用同一个流反复读写大量数据,将会造成大量的内部消耗,因此建议:
        1:调用clear()清除当前错误控制状态,其原型为 void clear (iostate state=goodbit);
        2:调用str("")将缓冲区清零,清除脏数据

      在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。 

    //验证字符串流不会主动释放内存
    #include <iostream>
    #include <sstream>
    #include <iomanip>
    using namespace std;
    int main()
    {
        ostringstream foo("hello world");
        cout<<foo.str()<<endl;        //hello world
        cout<<foo.str()<<endl;        //hello world
    
        istringstream bar("hello world");
        string word;
        while(bar>>word)
            cout<<word;               //helloworld
        cout<<endl;    
        cout<<bar.str()<<endl;        //hello world
    
        stringstream ss;
        string str;
        while(1)
        {
            ss<<"abcdefg";
            ss>>str;
            cout<<"Size of stream = "<<ss.str().length()<<endl;        //7
    14
    21
    28...
            ss.clear();            //重复使用同一字符串流,注意clear()
             system("pause");
        }
        system("pause");
        return 0;
    }
    //清除错误标识及清空string buffer
    #include <iostream>
    #include <sstream>
    #include <iomanip>
    using namespace std;
    int main()
    {
        stringstream ss("hello world");
        char ch;
        while(ss.get(ch))
            cout<<ch;                  //hello world
        cout<<endl;
    
        ss.clear();                    //清除ss.get()置位的failbit
        ss.str("");                    //清空string buffer
        ss<<"hello c++";    
        cout<<ss.str()<<endl;
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    二叉树的遍历以及创建——by leona
    利用图像压缩模型抵御对抗样本 by ch
    卡尔曼滤波器及其扩展的个人学习笔记~
    用GAN进行图像压缩 by ch
    用深度学习进行图像压缩 by ch
    3D目标检测&6D姿态估计之SSD-6D算法--by leona
    如何搭建三维重建工程体系
    C++面对对象(一)
    Pybind11教程
    C++的debug和release区别
  • 原文地址:https://www.cnblogs.com/kevinq/p/4508126.html
Copyright © 2011-2022 走看看