在std :: map中使用std :: tm作为Key

Inc*_*bus 5 c++ key map function-object

我想使用std :: tm()作为std :: map-container的键.但是当我尝试编译它时,我得到了很多(10)错误.

例如:

1.

错误C2784:'bool std :: operator <(const std :: basic_string <_Elem,_Traits,_Alloc>&,const _Elem*)':无法推断'const std :: basic_string <_Elem,_Traits,_Alloc>的模板参数&'from'const tm'c:\ program files(x86)\ microsoft visual studio 10.0\vc\include\xfunctional 125

2.

错误C2784:'bool std :: operator <(const _Elem*,const std :: basic_string <_Elem,_Traits,_Alloc>&)':无法从'const tm'c:\中推断'const _Elem*'的模板参数程序文件(x86)\ microsoft visual studio 10.0\vc\include\xfunctional 125

3.

错误C2784:'bool std :: operator <(const std :: vector <_Ty,_Ax>&,const std :: vector <_Ty,_Ax>&)':无法推断'const std :: vector <的模板参数_Ty,_Ax>&'from'const tm'c:\ program files(x86)\ microsoft visual studio 10.0\vc\include\xfunctional 125

这一切是否意味着,我"只是"必须创建一个比较两个std :: tm的函数对象,因为没有为此定义的标准比较?还是有另一招?(或者对我来说甚至可能不可能?^^)

码:

#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;
};
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 8

std::map使用比较器检查密钥是否已存在.所以当你使用时std::tm,你也要提供一个比较器作为第三个参数.

template < class Key, class T, class Compare = less<Key>,
           class Allocator = allocator<pair<const Key,T> > > class map
Run Code Online (Sandbox Code Playgroud)

因此,解决方案将是functor(正如您已经猜到的那样):

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!
Run Code Online (Sandbox Code Playgroud)

或者将自由函数(operator <)定义为:

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!
Run Code Online (Sandbox Code Playgroud)