条款19 了解相等和等价的区别
了解相等和等价的区别
例如find函数,或者一个set容器插入一个值得时候都会进行比较。但是它们的行为是不同的,find是通过 operator==,而set::insert对于相同的定义是等价,基于operator<。
接下来实现一个set,它可以存放不区分大小写的string。
先看看书上的版本:
//忽略大小写
struct CIStringCompare : binary_function<string, string, bool>
{
public:
bool operator()(const string& lhs, const string& rhs)
{
//忽略大小写比较函数
return stringCompareIgnoreCase(lhs.c_str(), rhs.c_str());
}
};
//使用如下
set<string, CIStringCompare> s;
s.insert("str");
s.insert("Str");
s.insert("sTr");
for (const string& str: s)
{
cout << str << " ";
}
cout << endl;
正如我们所想的一样,set容器只有一个值是”str”。
在新版的c++11中已经放弃了binary_function。在c++17更是把他移除了,同样移除的还包括:point_to_binary_function,ptr_fun等等。
实际上我们不继承binary_function,也可以实现同样的行为,这也是仿函数。
(如有不正确的地方,欢迎指出)