首页 > 代码库 > c++中在执行期指定排序准则
c++中在执行期指定排序准则
1 //定义排序准则的仿函数 2 template<class T> 3 class RuntimeCmp 4 { 5 public: 6 enum cmp_mode { _normal, _reverse}; 7 public: 8 RuntimeCmp(cmp_mode m = _normal) : mode(m){} 9 10 bool operator() (const T &t1, const T &t2) const{ return mode == _normal ? t1 < t2 : t2 < t1;}//重载()操作符11 bool operator== (const RuntimeCmp &rc){ return mode == rc.mode;}12 13 private:14 cmp_mode mode;15 };16 17 int main()18 {19 typedef set<int, RuntimeCmp<int> > IntSet;20 IntSet coll1;21 coll1.insert(4);22 coll1.insert(7);23 coll1.insert(5);24 coll1.insert(1);25 coll1.insert(6);26 coll1.insert(2);27 coll1.insert(5);28 cout << "coll1: ";29 copy(coll1.begin(), coll1.end(), ostream_iterator<int>(cout, " "));30 cout << endl;31 32 RuntimeCmp<int> reverse_order(RuntimeCmp<int>::_reverse);33 34 IntSet coll2(reverse_order);35 coll2.insert(4);36 coll2.insert(7);37 coll2.insert(5);38 coll2.insert(1);39 coll2.insert(6);40 coll2.insert(2);41 coll2.insert(5);42 43 cout << "coll2: ";44 copy(coll2.begin(), coll2.end(), ostream_iterator<int>(cout, " "));45 cout << endl;46 47 coll1 = coll2;48 coll1.insert(3);49 cout << "coll1: ";50 copy(coll1.begin(), coll1.end(), ostream_iterator<int>(cout, " "));51 cout << endl;52 53 //测试coll1和coll2排序准则是否相同54 if(coll1.value_comp() == coll2.value_comp())55 {56 cout << "coll1 and coll2 have same sorting criterion" << endl;57 }58 else59 {60 cout << "coll1 and coll2 have different sorting criterion" << endl;61 }
程序输出:
coll1: 1 2 4 5 6 7
coll2: 7 6 5 4 2 1
coll1: 7 6 5 4 3 2 1
coll1 and coll2 have same sorting criterion
注:赋值操作符同时也赋值了排序准则
详见c++标准程序库
c++中在执行期指定排序准则
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。