这个alue_comp()函数的返回值是什么?

#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()这个函数的返回值是什么,请说的详细点,谢谢。

慕沐林林
浏览 80回答 1
1回答

森栏

1、在什么地方调用了?在set.insert()的时候由set内部调用的。map和set这种关联式容器,本质是一个红黑树,你给它指定一个仿函数作为元素的比较准则,然后每次插入或删除数据的时候都会调用这个比较准则来决定在哪里插入或删除。查询的时候也会根据这个比较准则来搜寻元素。2、value_comp()返回值是什么?返回值就是你这个set当前所使用的判断准则。其类型根据你定义的时候的模版参数不同而不同,你这个例子中是RuntimeCmp<int>类型,coll2.value_comp()返回的值是与reverse_order相等的一个对象。
打开App,查看更多内容
随时随地看视频慕课网APP