首页 > 代码库 > 关联容器执行器指定排序规则

关联容器执行器指定排序规则

////  main.cpp//  setcmp////  Created by IDM-PKU on 14-9-6.//  Copyright (c) 2014年 PKU. All rights reserved.//#include <iostream>#include <set>#include "print.hpp"using namespace std;template <class T>class RuntimeCmp{    public:    enum cmp_mode{normal,reverse};    private:    cmp_mode mode;    public:    RuntimeCmp(cmp_mode m=normal):mode(m)    {}    bool operator()(const T& t1, const T& t2) const    {        return (mode==normal) ? (t1<t2) : (t2<t1);    }        bool operator==(const RuntimeCmp& rc)    {        return mode==rc.mode;    }    };typedef set<int,RuntimeCmp<int>> IntSet;void fill(IntSet & set);int main(int argc, const char * argv[]){    IntSet coll1;    fill(coll1);    PRINT_ELEMENTS(coll1,"coll1: ");    RuntimeCmp<int> reverse_order(RuntimeCmp<int>::reverse);        IntSet coll2(reverse_order);    fill(coll2);    PRINT_ELEMENTS(coll2,"coll2: ");        coll1=coll2;    coll1.insert(3);    PRINT_ELEMENTS(coll1,"coll1: ");    if(coll1.value_comp()==coll2.value_comp())    {        cout << "coll1 and coll2 have same sorting criterion" << endl;    }    else    {        cout << "coll1 and coll2 have different sorting criterion" << endl;    }    return 0;}void fill(IntSet & set){    set.insert(4);    set.insert(7);    set.insert(5);    set.insert(1);    set.insert(6);    set.insert(2);    set.insert(5);}

注意容器赋值时不仅赋值了元素,也赋值了排序规则。

这种技术使得程序执行期才获得排序准则,而且set容器用到不同的排序准则,但其数据型别是相同的。

程序在Mac OS下的运行结果如下:

关联容器执行器指定排序规则