STL库基本数据算法的使用(一)

来源:互联网 发布:2个excel表格数据比对 编辑:程序博客网 时间:2024/06/05 06:46
/*  STL单纯的数据处理算法**  2017.2.21 18:00**  by 51CC   张卓*/#include<iostream>#include<vector>#include<algorithm>#include<functional>#include<iterator>using namespace std;void print(int n){    cout<<n<<' ';    }bool greater5(int n){    return n > 5;           }int sum(int n){    return n+n;    }struct Print    //struct默认成员公有{    void operator()(int n)    {        cout<<n<<' ';    }};class Great{public:    Great(int n) : value(n){}    bool operator()(int m)    {        return value < m;    }private:    int value;};int main(){    int a[10] = {100,3,45,6,78,7,7,8,13,22};    int n = sizeof(a) / sizeof(a[0]);    vector<int> vt(a, a+n);    vector<int> b;    //copy   copy_if    sort    copy(a, a+7, vt.begin());    sort(vt.begin(), vt.end());    copy(vt.begin(), vt.end(), ostream_iterator<int>(cout, " "));    cout<<endl;    sort(vt.begin(), vt.end(), greater<int>());    copy_if(vt.begin(), vt.end(), back_insert_iterator<vector<int> >(b), Great(22));    for_each(b.begin(), b.end(), print);    cout<<endl;    //for_each    for_each(vt.begin(), vt.end(), print);    cout<<endl;    for_each(vt.begin(), vt.end(), Print());    cout<<endl;    //find  find_if打印所有大于2的数    vector<int>::iterator iter;    iter = find(vt.begin(), vt.end(), 2);    cout<<*(iter-1)<<endl;    iter = find_if(vt.begin(), vt.end(), Great(22));    while(iter != vt.end())    {        cout<<*iter<<' ';        iter++;        iter = find_if(iter, vt.end(), Great(22));    }    cout<<endl;    //count count_if push_back    vt.push_back(2);    vt.push_back(2);    vt.push_back(2);    int num = count(vt.begin(), vt.end(), 2);    cout<<num<<endl;    num = count_if(vt.begin(), vt.end(), Great(2));    cout<<num<<endl;    //移除remove    remove_if    cout<<"remove"<<endl;    for_each(vt.begin(), vt.end(), print);    cout<<endl;    remove(vt.begin(), vt.end(), 78);        //移除的元素会放在最后一个位置,应手动给end-1    for_each(vt.begin(), vt.end()-1, print);    cout<<endl;    //replace   replace_if    for_each(b.begin(), b.end(), print);    cout<<endl;    replace(b.begin(), b.end(), 100, 3);    for_each(b.begin(), b.end(), print);    cout<<endl;    for_each(vt.begin(), vt.end(), print);    cout<<endl;    replace_if(vt.begin(), vt.end(), Great(2), 100);     for_each(vt.begin(), vt.end(), print);    cout<<endl;    //transform将前两个区间内的元素用第四个函数操作后放到以第三个参数开始的容器中    vector<int> c(vt.begin(), vt.end());    transform(vt.begin(), vt.end(), c.begin(), sum);    for_each(c.begin(), c.end(), print);    cout<<endl;    //reverse    reverse(c.begin(), c.end());    for_each(c.begin(), c.end(), print);    cout<<endl;    //swap_ranges    cout<<"-------------------------------"<<endl;    for_each(vt.begin(), vt.end(), print);    cout<<endl;    for_each(b.begin(), b.end(), print);    cout<<endl;    swap_ranges(b.begin(), b.end(), vt.begin());     for_each(vt.begin(), vt.end(), print);    cout<<endl;    for_each(b.begin(), b.end(), print);}
1 0
原创粉丝点击