另外:operator() 、operator== 在程序中是究竟是怎样被调用的#include <iostream> #include <set> using namespace std; template <class T> class RuntimeCmp { public: enum cmp_mode {normal, reverse}; private: cmp_mode mode; public: //constructor for sorting criterion //-default criterion uses value normal RuntimeCmp (cmp_mode m=normal) : mode(m) { } //comparision of elements bool operator() (const T& t1, const T& t2) const { return mode == normal ? t1 < t2 : t2 < t1; } //comparision of sorting criteria bool operator== (const RuntimeCmp& rc) { return mode == rc.mode; } }; //type of a set that uses this sorting criterion typedef set<int,RuntimeCmp<int> > IntSet; void fill (IntSet& Set) { //fill insert elements in random order Set.insert(4); Set.insert(7); Set.insert(5); Set.insert(1); Set.insert(6); Set.insert(2); Set.insert(5); } template <class T> int main() { //create, fill, and print set with normal element order //-uses default sorting criterion IntSet coll1; fill(coll1); copy(coll1.begin(),coll1.end(),ostream_iterator<int>(cout," "));cout<<endl;RuntimeCmp<int> reverse_order(RuntimeCmp<int>::reverse); //create, fill, and print set with reverse element order IntSet coll2(reverse_order); fill(coll2); copy(coll2.begin(),coll2.end(),ostream_iterator<int>(cout," "));cout<<endl;//assign elements AND sorting criterion coll1 = coll2; coll1.insert(3); // PRINT_ELEMENTS coll1copy(coll1.begin(),coll1.end(),ostream_iterator<int>(cout," "));cout<<endl;//just to make sure... 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;}
- 2 回答
- 0 关注
- 125 浏览
添加回答
举报
0/150
提交
取消