Using std :: tm as Key in std :: map

I would like to use std :: tm () as the key for std :: map-container. But when I try to compile it, I get a lot of errors (10).

For instance:

1.

error C2784: 'bool std :: operator <(Const stand :: basic_string <_Elem, _Traits, _Alloc> &, const _Elem *)': the template argument for 'const standard :: basic_string <_Elem, _Traits, _Alloc> could not be output & Amp; "from 'const tm' c: \ program files (x86) \ Microsoft Visual Studio 10.0 \ vc \ include \ xfunctional 125

2.

error C2784: 'bool std :: operator <(const _Elem *, const std :: basic_string <_Elem, _Traits, _Alloc> &)': the template argument for 'const _Elem *' could not be derived from 'const tm' c: \ program files (x86) \ Microsoft Visual Studio 10.0 \ vc \ include \ xfunctional 125

3.

error C2784: 'bool std :: operator <(const std :: vector <_Ty, _Ax> &, const std :: vector <_Ty, _Ax> &)': could not print the template argument for 'const std :: vector < _Ty, _Ax> & 'by' const tm 'c: \ program files (x86) \ microsoft visual studio 10.0 \ vc \ include \ xfunctional 125

Does all this mean that I "just" have to create a function object that compares two std :: tm, because there is no standard comparison for this? Or is there another trick? (or maybe even impossible for me? ^^)

code:

#include <map> #include <ctime> #include <string> int main() { std::map<std::tm, std::string> mapItem; std::tm TM; mapItem[TM] = std::string("test"); return 0; }; 
+4
source share
4 answers

std::map uses a comparator to check if a key exists or not. Therefore, when you use std::tm , you should also provide a comparative example as the third argument.

 template < class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key,T> > > class map 

So the solution will be a functor (you guessed it):

 struct tm_comparer { bool operator () (const std::tm & t1, const std::tm & t2) const { //^^ note this //compare t1 and t2, and return true/false } }; std::map<std::tm, std::string, tm_comparer> mapItem; //^^^^^^^^^^ pass the comparer! 

Or define a free function ( operator < ) as:

 bool operator < (const std::tm & t1, const std::tm & t2) { // ^ note this. Now its less than operator //compare t1 and t2, and return true/false }; std::map<std::tm, std::string> mapItem; //no need to pass any argument now! 
+8
source

Yes, std::tm does not define the < operator.

+2
source

Enough free function, you do not need a function object.

+2
source

Yes, you need to define the <operator for the tm structure. see http://www.cplusplus.com/reference/stl/map/map/ , for example (at the bottom of the page).

+2
source

All Articles