关联容器
本文介绍在关联容器中常见的一些的问题以及提升使用关联容器的建议。
1. 理解相等(equality)和等价(equivalence)的区别。
相等是以operator==为基础的。等价是以operator<为基础的。
例如find的定义是相等,他用operator==来判断,这是比较容易理解的。
而等价关系是以“在已排序的区间中对象值的相对顺序”为基础的。也就是说,如果两个值中任何一个(按照既定的排列顺序)都在另一个的前面,那么他们就是等价的。
!(w1 < w2) && !(w2 < w1);
!c.key_comp()(x, y) && !c.key.comp(y, x);
key_comp()
返回一个函数,并以x, y作为参数传入。
具体而言,我们设想一个不区分string大小的set,来具体说明问题。
#include <iostream>
#include <set>
#include <string>
using namespace std;
bool ciCharLess(char c1, char c2) {
// 在C++中,char可能是有符号的也可能是无符号的,所以我们要转换为无符号的char,才能比较。
return tolower(static_cast<unsigned char> (c1)) <
tolower(static_cast<unsigned char> (c2));
}
bool ciStringCompare(const string& s1, const string& s2) {
return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), ciCharLess);
}
// It must be a struct but not be a class.
struct CIstring : public binary_function<string, string, bool> {
bool operator() (const string& T1, const string& T2) const {
return ciStringCompare(T1, T2);
}
};
int main(int argc, char *argv[]) {