Effective STL 19 understand the difference between equality and equivalence

来源:互联网 发布:怎么查询扣分情况淘宝 编辑:程序博客网 时间:2024/05/14 06:14
  1. Equivalence is defined in terms of comparison function(!(w1 < w2) && !(w2 < w1)), so clients of a standard associative container need to only one comparison function.

  2. set wants a comparison function type, not an actual function. To bridge this gap, we write a functor class whose operator() calls ciStringCompare:

ciStringCompare

int ciCharCompare(char c1, char c2) {    // in both C and C++, char may or may not be signed, the only way to     // ensure that its value is representable as an unsigned char is to cast    int lc1 = tolower(static_cast<unsigned char>(c1));    int lc2 = tolower(static_cast<unsigned char>(c2));    if (lc1 < lc2) return -1;    if (lc1 > lc2) return 1;    return 0;}int ciStringCompareLmpl(const string& s1, const string& s2) {    typedef pair<string::const_iterator, string::const_iterator> PSCI;    // mismatch will stop when the predicate returns false    PSCI p = mismatch(s1.begin(), s1.end(), s2.begin(), not2(ptr_fun(ciCharCompare)));    // s1 is short than s2    if (p.first == s1.end) {        if (p.second == s2.end) return 0;        else return -1;    }    return ciCharCompare(*p.first, *p.second);}int ciStringCompare(const string& s1, const string& s2) {    if (s1.size() <= s2.size()) return ciCharCompare(s1, s2);    else return ciCharCompare(s2, s1);}
struct CIStringCompare: // also see item 40    public    binary_function<string, string, bool> {     bool operator()(const string& lhs, const string& rhs) const {        return ciStringCompare(lhs, rhs); // also see item 35        }    };set<string, CIStringCompare> ciss;ciss.insert("Persephon");ciss.insert("persephon"); // no new element is added to the set// the standard associative constainers are kept in sorted order, so each container// must have a comparsion function. Equivalence is defined in terms of this comparison function.if (ciss.find("persephone") != ciss.end()) ... // this test will succeed                                               // equivalenceif (find(ciss.begin(), ciss.end(), "persephone") // fail                                                  // equality                                                 // string("persephon") != string("Persephon")
原创粉丝点击