使用 std::tm 作为 std::map 中的键

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

本文关键字:std 作为 tm 使用 map      更新时间:2023-10-16
我想使用 std::

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

例如:

1.

错误 C2784: 'bool std::运算符 <(常量) 标准::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : 无法推断 "常量"的模板参数 标准::basic_string<_Elem,_Traits,_Alloc> &' 来自 'const TM' c:\program files (x86)\Microsoft Visual Studio 10.0\vc\include\x功能 125

阿拉伯数字。

错误 C2784: 'bool std::运算符 <(常量_Elem *,常量 标准::basic_string<_Elem,_Traits,_Alloc> &)' : 无法推断模板 "常量 _Elem *"的参数来自 'const tm' c:\program files (x86)\Microsoft Visual Studio 10.0\vc\include\x功能 125

3.

错误 C2784: 'bool std::运算符 <(const std::vector<_Ty,_Ax> &,const std::vector<_Ty,_Ax> &)' : 不能 推导 'const 的模板参数 std::vector<_Ty,_Ax> &' 来自 'const TM' C:\Program Files (x86)\Microsoft 视觉工作室 10.0\vc\include\x功能 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;
};

>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!
是的

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

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

是的,您需要为 TM 结构定义运算符<。 例如,请参阅 http://www.cplusplus.com/reference/stl/map/map/(页面底部)。