I have a map with string date-time keys, and int values. I would like to sort my map by the date and time (by the map keys actually) which are in format like this: 30/11/2012:13:49:55
. Is that possible? How to sort them? When sorting only string there's no such a big deal, but I really don't know how to do this with date/time string.
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<string, int> mymap;
mymap["30/11/2012:13:49:09"] = 122;
mymap["30/11/2012:13:49:55"] = 100;
mymap["30/11/2012:13:49:12"] = 123;
mymap["29/11/2012:19:26:11"] = 45;
for (std::map<string, int>::iterator i = mymap.begin(); i != mymap.end(); i++)
{
cout << i->first << "\n";
}
};
The output of the program suggests that this map is already ordered, however, I'm not quite sure if it always (in every case) sort it like I want it to.
Ok folks, will something like this work fine?
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
time_t string_to_time_t(string s)
{
struct tm tmp;
time_t t;
memset(&tmp, 0, sizeof(struct tm));
strptime(s.c_str(), "%d/%m/%Y:%H:%M:%S", &tmp);
t = mktime(&tmp);
return t;
}
int main()
{
time_t t, u;
t = string_to_time_t("30/11/2012:13:49:09");
u = string_to_time_t("30/11/2012:13:49:08");
if (u>t)
{
cout << "true" << endl;
}
else if (u==t)
{
cout << "same" << endl;
}
else
{
cout << "false" << endl;
}
return 0;
}
EDIT:
Huh, it seems to work now, thanks!
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <map>
using namespace std;
time_t string_to_time_t(string s)
{
struct tm tmp;
time_t t;
memset(&tmp, 0, sizeof(struct tm));
strptime(s.c_str(), "%d/%m/%Y:%H:%M:%S", &tmp);
t = mktime(&tmp);
return t;
}
int main()
{
map<time_t, int> mymap;
mymap[string_to_time_t("30/11/2012:13:49:09")] = 122;
mymap[string_to_time_t("30/11/2012:13:49:55")] = 100;
mymap[string_to_time_t("30/11/2012:13:49:12")] = 123;
mymap[string_to_time_t("29/11/2012:19:26:11")] = 45;
for (std::map<time_t, int>::iterator i = mymap.begin(); i != mymap.end(); i++)
{
cout << i->first << " " << i->second << "\n";
}
};