C++ sort string in comparator function

Hello there i am currently using a comparator function in STL map for sorting date of string data type in ascending value. My dates are in this format for e.g. 15OCT1990, 13SEP1980 and etc. I am using substring to split up the string so i can compare day, month, year separately. So now i have problem comparing the month portion because alphabetically "FEB" comes before "JAN". I have been thinking for hours but couldn't come up with a solution. Please advice what can i add to my current code, thanks!

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
struct sortMapDaily: public std::binary_function <bool, std::string, std::string>
{

  bool operator() (const std::string& lhs, const std::string& rhs)
  {

     if(lhs.substr(5,4) < rhs.substr(5,4))
     {
         return true;

     }
     else if (lhs.substr(5,4) == rhs.substr(5,4) && lhs.substr(2,3) < rhs.substr(2,3))
     {

         return true;
     }
     else if (lhs.substr(5,4) == rhs.substr(5,4) && lhs.substr(2,3) == rhs.substr(2,3) && lhs.substr(0,2) < rhs.substr(0,2))
     {
         return true;

     }
     else
     {
         return false;
     }


  }
};
Last edited on
You may want to make a map that associates the month name with the month number so that you can compare those. Then just look up the name and sort based on that value.
Like this?
map<string,int>compareMonth;
compareMonth["JAN"] = 1;
compareMonth["FEB"] = 2;


But how do i pass the value to the condition lhs.substr(2,3) < rhs.substr(2,3) so that it knows "JAN" is less than "FEB"?
If lhs/rhs.substr(2,3) is the name of the month, then you can just check the same way you assigned: compareMonth[lhs.substr(2,3)] will return 1 if lhs.substr(2,3) is "JAN" and so on.
Topic archived. No new replies allowed.