假定有一个string*指针的set,你把一些动物的名字插入set:
set<string*> ssp;
ssp.insert(new string("Anteater"));
ssp.insert(new string("Wombat"));
ssp.insert(new string("Lemur"));
ssp.insert(new string("Penguin"));
一、比较仿函数的实现
方法1:实现自己的比较仿函数类,它的对象带有string*指针并按照指向的字符串值来进行排序。就像这样:
struct StringPtrLess : public binary_function<const string*,
const string*,
bool>{
bool operator()(const string *ps1, const string *ps2) const
{
return *ps1 < *ps2;
}
}
typedef set<string*, StringLessPtr> StringPtrSet;
StringPtrSet ssp;
ssp.insert(new string("Anteater"));
ssp.insert(new string("Wombat"));
ssp.insert(new string("Lemur"));
ssp.insert(new string("Penguin"));
方法2:使用比较的仿函数模板
struct DeferenceLess {
template<typename PtrType> // 参数是值传递的,
bool operator()()(PtrType pT1, PtrType pT2) const // 因为我们希望它们
{ // 是(或行为像)指针
return *pT1 < *pT2;
}
};
set<string*, DeferenceLess> ssp; // 行为就像
// set<string*, StringPtrLess>
...
二、打印函数的实现
方法1:使用for_each函数
void print(const string *ps)
{
cout << *ps << endl; // 把ps指向的对象打印到cout
}
for_each(ssp.begin(), ssp.end(), print); // 在ssp中的每个元素上调用print
方法2:使用泛型的解引用仿函数类,用它和transfom与ostream_iterator连用
// 当本类型的仿函数被传入一个T*时,它们返回一个const T&
struct Deference {
template<typename T>
const T& operator()(const T *ptr) const
{
return *ptr;
}
};
transform(ssp.begin(), ssp.end(), // 通过解引用”转换“
ostream_iterator<string>(cout, "\n"), // ssp中的每个元素
Deference()); // 把结果写入cout
该方案也可应用于表现为指针的对象的容器,例如,智能指针和迭代器。