I'd like to use std::tm () as the key for an std::map-container. But when I try to compile it, I get a lot(10) of errors.
For example:
1.
error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' 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> &)' : could not deduce template argument for 'const _Elem *' 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 deduce template argument for 'const std::vector<_Ty,_Ax> &' from 'const tm' c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional 125
Does all this mean, that I "simply" have to created an function object which compares two std::tm, because there is no standard-comparison defined for this? Or is there another trick? (or may it even be impossible to 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;
};
std::map
uses a comparer to check if the key already exists or not. So when you use std::tm
, you've to provide a comparer as third argument as well.
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > > class map
So a solution would be functor (as you already guessed):
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With