'Sorting dates (string) stored in vector
I have a vector that contains dates in this format, DDMMMYY, e.g 12Jan14
vector<string> tempDate
When I use the STL sort, basically it will work when all of the dates are in the same year/month. 01Jan14, 05Jan14, 11Jan14, etc. But when I enter 02Feb14, it will all be messed up.
sort (tempDate.begin(), tempDate.end())
Can anyone tell me what went wrong with it?
Edit: I tried to use templates, but it doesn't work as all the string got 'split' up. I did some troubleshooting inside the sortDayMonthYear
template <class T>
bool sortDayMonthYear(T a, T b)
{
for (int i =0; i < a.size(); i++)
cout << a.at(i)<< endl;
}
What i get is something like this
0
1
J
A
N
1
4
0
2
J
A
N
1
4
Actually what I intend to do is to pass the two strings into the template function, using substr to get the day, month, year, compare and return true or false.
Solution 1:[1]
Your predicate should take two constant string references as argument, and then use those to decide which one is "lesser" than the other.
So:
bool sortDayMonthYear(const std::string& first, const std::string& second)
{
// Algorithm to find out which string is "lesser" than the other
}
Then you use that comparator function when sorting:
std::sort(std::begin(tempDate), std::end(tempDate), sortDayMonthYear);
Solution 2:[2]
The standard way of sorting strings is lexicographical (by alphabet, for each letter, just like in a dictionary).
Therefore, what you need is your own comparator. There is a version of sort which takes one as third parameter. See e.g. this question for starting ideas: Sorting a vector of custom objects
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Some programmer dude |
| Solution 2 | Community |
