标签:
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 else 59 { 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++标准程序库
标签:
原文地址:http://www.cnblogs.com/zuopeng0943/p/5946590.html