zoukankan      html  css  js  c++  java
  • [c++] stringstream的用法

    [1] 用于分割被空格、制表符等符号分割的字符串

    #include<iostream>  
    #include<sstream>        //istringstream 必须包含这个头文件
    #include<string>  
    using namespace std;  
    int main()
    {  
        string str="i am a boy";  
        stringstream is(str);  
        string s;  
        while(is>>s)
            cout<<s<<endl;  
    } 
    

    [2]将分割的字符串保存到vector

    void splitstring (const string &str, char separator, vector<string> &vec)
    {	//分隔符可以为",",或斜杠
    	std::string word;
    	std::stringstream stream (str);
    
    	vec.clear();
    
    	while (std::getline (stream, word, separator))
    	{
    		vec.push_back (word);
    	}
    }
    

    [3]内存管理

    由于stringstream构造函数会特别消耗内存,似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )。

    另外不要企图用 stream.str().resize(0),或 stream.str().clear() 来清除缓冲,使用它们似乎可以让stringstream的内存消耗不要增长得那么快,但仍然不能达到清除stringstream缓冲的效果,内存的消耗还在缓慢的增长!,至于stream.flush(),则根本就起不到任何作用。

  • 相关阅读:
    hdu 5335 Walk Out (搜索)
    Hdu 5336 XYZ and Drops (bfs 模拟)
    Zznu 1913: yifan and matrix (多路归并)
    hdu 5316 Magician (线段树)
    Bzoj 2038: [2009国家集训队]小Z的袜子(hose)
    Poj 1741 Tree (树的分治)
    LightOJ 1027
    1067
    Closest Common Ancestors---poj1470(LCA+离线算法)
    1128
  • 原文地址:https://www.cnblogs.com/P3nguin/p/10239229.html
Copyright © 2011-2022 走看看