C++ STL简单小程序之开源中国

来源:互联网 发布:网店系统源码 编辑:程序博客网 时间:2024/05/16 16:12

1、字符串分割:

#include <iostream>#include <string>#include <vector>using namespace std;vector<string> split(const string&s){    vector<string> ret;    typedef string::size_type string_size;    string_size i = 0;    while (i != s.size()){        while (i != s.size() && isspace(s[i]))            ++i;        string_size j = i;        while (j != s.size() && !isspace(s[j]))            ++j;        if (j != i){            ret.push_back(s.substr(i, j - i));            i = j;        }    }    return ret;}int main(){    string s;    while (getline(cin, s)){        vector<string> v = split(s);        cout << "\n分割为:" << v.size()<< "个字符\n";        for (vector<string>::iterator i = v.begin(); i!=v.end(); i++){            cout << *i << endl;        }        cout << endl;    }    return 0;}

运行结果:
这里写图片描述

2、两个stack实现一个queue

#include <iostream>#include <string>#include <stack>#include <vector>using namespace std;template <typename T>class queue_self{public:    void enqueue(T t);    T dequeue();    bool isEmpty();private:    stack<T> s1, s2;};template <typename T>void queue_self<T>::enqueue(T t){    s1.push(t);}template <typename T>T queue_self<T>::dequeue(){    T t;    while (!s1.empty()){        s2.push(s1.top());        s1.pop();    }    if (!s2.empty()){        t = s2.top();        s2.pop();    }    return t;}template <typename T>bool queue_self<T>::isEmpty(){    return s1.empty() && s2.empty();}vector<string> split(const string&s){    vector<string> ret;    typedef string::size_type string_size;    string_size i = 0;    while (i != s.size()){        while (i != s.size() && isspace(s[i]))            ++i;        string_size j = i;        while (j != s.size() && !isspace(s[j]))            ++j;        if (j != i){            ret.push_back(s.substr(i, j - i));            i = j;        }    }    return ret;}int main(){    queue_self<string> qs;    vector<string> qs_show;    /*    string s;    while (cin>>s){        qs.enqueue(s);    }    */    string s;    vector<string> ret;    while (getline(cin, s)){        ret = split(s);    }    for (vector<string>::size_type i = 0; i != ret.size(); i++){        qs.enqueue(ret[i]);    }    cout << "看看queue_self的输出:" << endl;    while (!qs.isEmpty()){        qs_show.push_back(qs.dequeue());    }    for (vector<string>::iterator i = qs_show.begin(); i != qs_show.end(); i++){        cout << *i << " ";    }    cout << endl;    return 0;}

运行结果:
这里写图片描述

原创粉丝点击