开发者

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

开发者 https://www.devze.com 2023-03-05 04:42 出处:网络
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.

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>开发者_JAVA技巧 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!


Yes std::tm doesn't define a < operator.


A free function suffices, you do not need a function object.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号