您的位置:首页 > 产品设计 > UI/UE

Effective STL 19 understand the difference between equality and equivalence

2017-08-27 18:48 381 查看
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.

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
// equivalence

if (find(ciss.begin(), ciss.end(), "persephone") // fail
// equality
// string("persephon") != string("Persephon")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: