Check the following code:
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 LeagueComparator
{
public:
bool operator()(const string& s1, const string& s2)
{
return toLowerCase(s1) < toLowerCase(s2);
}
};
int main()
{
set<string, LeagueComparator> leagues;
set<string, LeagueComparator>::iterator iter;
leagues.insert("BLeague");
leagues.insert("aLeague"); // leagues = {"aLeague", "BLeague"}
leagues.insert("ALeague");
for (iter = leagues.begin(); iter != leagues.end(); iter++)
cout << *iter << endl;
return 0;
}
The output is:
aLeague
BLeague
which is shocking to me. I thought (and expecting) the output would be:
aLeague
ALeague
BLeague
Before the execution of leagues.insert("ALeague");
, the leagues
contains "aLeague"
and "BLeague"
. My question is, while executing leagues.insert("ALeague");
why the machine treats "ALeague" == "aleague"
? According to my understanding, there is no element "ALeague"
in leagues
. So "ALeague"
should be inserted into leagues
. The comparator should determine where to put "ALeague"
.
Thanks in advance.
PS: Please don't hit me for using C style cast. :P I'm too lazy to type static_cast
.