[英]Using std::tm as Key in std::map
我想使用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;
};
std::map
使用比较器来检查密钥是否已存在。 所以当你使用std::tm
,你也要提供一个比较器作为第三个参数。
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > > class map
因此,解决方案将是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!
或者将自由函数( 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
没有定义<
运算符。
一个自由函数就足够了,你不需要一个函数对象。
是的,您需要定义operator <for tm结构。 例如,参见http://www.cplusplus.com/reference/stl/map/map/ (页面底部)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.