zoukankan      html  css  js  c++  java
  • "partition"和“stable_partition”的思考

    "partition"和“stable_partition”设计的目的是根据一个谓词而把容器分为两部分。可是他们具体的区别在哪里呢?下面我们来验证一下。

    void elimDups(vector<string> &words)
    {
        sort(words.begin(), words.end());
        auto it = unique(words.begin(),words.end());
        words.erase(it, words.end());
        for(auto &a : words) cout << a << " ";
        cout << endl;
    }
    void bigies_partition(vector<string> &words, std::size_t sz)
    {
        elimDups(words);
        auto pivot = partition(words.begin(),words.end(),
                               [sz](const string &a){return a.size() < sz;});
        for(auto a = words.begin(); a != pivot; ++a){
            cout << *a << " ";
        }
    }
    void bigies_stable_partition(vector<string> &words, std::size_t sz)
    {
        elimDups(words);
        auto pivot = stable_partition(words.begin(),words.end(),
                               [sz](const string &a){return a.size() < sz;});
        for(auto a = words.begin(); a != pivot; ++a){
            cout << *a << " ";
        }
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        vector<string> v{"aa", "c", "ffff","bb","dddddd","eee","aaa","bbb"};
    
    
        vector<string> v1(v);
        cout << "partition:" << endl;
        bigies_partition(v1,3);
        cout << endl;
    
        vector<string> v2(v);
        cout << "stable_partition:" << endl;
        bigies_stable_partition(v2,3);
        cout << endl;
    
        return a.exec();
    }

    output:

    partition
    aa aaa bb bbb c dddddd eee ffff
    aa c bb
    stable_partition
    aa aaa bb bbb c dddddd eee ffff
    aa bb c


    可以发现,stable_partition除了根据谓词把容器划分为两部分,还可以保持容器原有元素的顺序。

  • 相关阅读:
    servlet乱码以及解决
    javascript正则简单入门
    javascript创建自定义对象和prototype
    java 对象初始化和代码块初始化顺序
    java final 和instanceof 关键字
    【记录】自学JavaScript第七周
    【记录】自学JavaScript第六周
    获取节点名称及节点值
    正则表达式中的替换字符串示例
    部分正则表达式基本函数用法示例
  • 原文地址:https://www.cnblogs.com/vczf/p/6823257.html
Copyright © 2011-2022 走看看