我只是检查设置比较器的有效STL(书籍)示例以实现不区分大小写的设置,但我遇到了问题(visual studio说comaparator无效,但它在ideone中工作)。我确信在我的实施中存在一些问题,即使这样也不会让人感到困惑。
以下是代码
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
inline int ciCharCompare(char c1, char c2) // case-insensitively compare chars
{ // c1 and c2, returning -1 if c1 < c2,
//0 if c1==c2, and 1 if c1 > c2
int Ic1 = tolower(static_cast<unsigned char>(c1)); //see below for
int Ic2 = tolower(static_cast<unsigned char>(c2)); // info on these
if (Ic1 < Ic2) return -1;
if (Ic1 > Ic2) return 1;
return 0;
}
struct CiStringCompare : public std::binary_function<string, string, bool>
{
int ciStringCompareImpl(const string& s1, const string& s2) const
{
auto p = mismatch( //see below for an
s1.begin(), s1.end(), //explanation of why
s2.begin(), //we need not2;see
not2(ptr_fun(ciCharCompare))); //Item 41 for why we
// need ptr_fun
if (p.first == s1.end()) { //if true, either s1 and
if (p.second == s2.end()) return 0; // s2 are equal or
else return -1; //s1 is shorter than s2
}
return ciCharCompare(*p.first, *p.second);
}
int xxxx(const string& s1, const string& s2) const
{
if (s1.size() <= s2.size()) return ciStringCompareImpl(s1, s2);
else return -ciStringCompareImpl(s2, s1);
}
int operator()(const string& str1, const string& str2) const {
return xxxx(str1, str2);
}
};
class DifferenceBetweenEquivalenceandEquality
{
// Comparator functor
set<string, CiStringCompare> s;
public:
DifferenceBetweenEquivalenceandEquality(const vector<string>& v)
{
for (const auto& x : v)
s.insert(x);
}
void print() {
for(const auto& x: s)
cout << x << endl;
}
};
int main()
{
DifferenceBetweenEquivalenceandEquality dbee({ "STL","stl","aaa","bbb" });
dbee.print();
return 0;
}
虽然它在ideone中工作得很好,所以我对于什么使比较器有效以及每个这些的等式,等价和排序效果感到困惑。 例如::在正常情况下我得到
STL stl aaa bbb
但是使用下面的比较器我得到
aaa bbb stl STL
inline string toLowerCase(const string& str) {
string res(str);
int i;
for (i = 0; i < (int)res.size(); i++)
res[i] = (char)tolower(res[i]);
return res;
}
class NormalComparator
{
public:
bool operator()(const string& s1, const string& s2)
{
return toLowerCase(s1) < toLowerCase(s2) ||
!(toLowerCase(s2) < toLowerCase(s1)) && s1 < s2;
}
};