Problem with stl map with comparison class

Hi all, I am new to STL and I have a problem with my map. I made a class(Sort) for comparison on the map but the problem is map.find will not work or my keys are distroted or something.

Can someone explain why find was not able to locate the key?

here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<iostream>
#include<map>
#include<string>

using namespace std;
class Sort
{
public:
bool operator() (string const &_A, string const &_B) const
{
double num1, num2;
num1 = atoi(_A.c_str());
num2 = atoi(_B.c_str());
if( num1 && num2 ) {
if( num1 <= num2 )
return true;
else return false;
}
else {
if( _A.compare(_B) <= 0 ) return true;
else return false;
}
}
};

typedef map<string, string, Sort> EnumMap;

int main()
{
string str="A";
EnumMap months;
EnumMap::iterator it;
months["1"] = "January";
months["7"] = "July";
months["2"] = "February";
months["3"] = "March";
months["4"] = "April";
months["5"] = "May";
months["6"] = "June";
months["8"] = "August";
months["9"] = "September";
months["10"] = "October";
months["11"] = "November";
months["12"] = "December";

for ( it=months.begin() ; it!=months.end(); it++ ) {
cout << (*it).first << "==>" << (*it).second << endl;
}

EnumMap::iterator t2= months.find("7");
if(t2!=months.end())
cout << "Found" << endl;
else cout << "Not Found" << endl;
} 


Output:

1==>January
2==>February
3==>March
4==>April
5==>May
6==>June
7==>July
8==>August
9==>September
10==>October
11==>November
12==>December
Not Found

you have to implement the logic of "operator<" not "operator<=". Look at your line 15 and 20. You have to use "<" not "<=".


(Why is it that map don't find the elements: Map knows when it found your requested element if "!Sort(elem,search) && !Sort(search,elem)", which is the definition of equivalence (neither one is smaller than the other). But this statement is never true for your Sort, since it always return true for "Sort(x,x)".)

Ciao, Imi.
Topic archived. No new replies allowed.