5

我想使用 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> 的模板参数&' 来自 '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> &' 来自 '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;
};
4

4 回答 4

8

std::map使用比较器检查密钥是否已经存在。因此,当您使用 时std::tm,您还必须提供一个比较器作为第三个参数。

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

所以一个解决方案是仿函数(正如你已经猜到的):

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!

或者定义一个自由函数 ( 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!
于 2011-05-12T14:03:09.380 回答
2

Yesstd::tm没有定义<运算符。

于 2011-05-12T14:01:54.363 回答
2

一个自由函数就足够了,你不需要一个函数对象。

于 2011-05-12T14:02:53.957 回答
2

是的,您需要为 tm 结构定义 operator<。例如,参见http://www.cplusplus.com/reference/stl/map/map/(页面底部)。

于 2011-05-12T14:03:23.140 回答