#include <set>#include <iostream>#include "MyPrint.h"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, char * argv[]){IntSet coll1;fill(coll1);MyPrint(coll1, "coll1: ");RuntimeCmp<int> reverse_order(RuntimeCmp<int>::reverse);IntSet coll2(reverse_order);fill(coll2);MyPrint(coll2,"coll2: ");coll1 = coll2;coll1.insert(3);MyPrint(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;system("pause");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);}其中MyPrint函數就是個簡單打印函數,我想問在RuntimeCmp類中重寫的operator在后面的main中什么地方調用了,還有就是value_comp()這個函數的返回值是什么,請說的詳細點,謝謝。
1 回答

森欄
TA貢獻1810條經驗 獲得超5個贊
1、在什么地方調用了?
在set.insert()的時候由set內部調用的。map和set這種關聯式容器,本質是一個紅黑樹,你給它指定一個仿函數作為元素的比較準則,然后每次插入或刪除數據的時候都會調用這個比較準則來決定在哪里插入或刪除。查詢的時候也會根據這個比較準則來搜尋元素。
2、value_comp()返回值是什么?
返回值就是你這個set當前所使用的判斷準則。其類型根據你定義的時候的模版參數不同而不同,你這個例子中是RuntimeCmp<int>類型,coll2.value_comp()返回的值是與reverse_order相等的一個對象。
- 1 回答
- 0 關注
- 142 瀏覽
添加回答
舉報
0/150
提交
取消