#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函數(shù)就是個(gè)簡(jiǎn)單打印函數(shù),我想問(wèn)在RuntimeCmp類(lèi)中重寫(xiě)的operator在后面的main中什么地方調(diào)用了,還有就是value_comp()這個(gè)函數(shù)的返回值是什么,請(qǐng)說(shuō)的詳細(xì)點(diǎn),謝謝。
1 回答

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