使用 std::tm 作为 std::map 中的键
Using std::tm as Key in std::map
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/(页面底部)。
- C++匿名结构作为std::映射值
- 为什么 std::function 可以作为 std::not2 的参数?
- std::vector::迭代器是否可以合法地作为指针
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- std::ofstream 作为类成员删除复制构造函数?
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- std::span<const T> 作为函数模板中的参数
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 使用 std::async 时死锁,将来作为成员
- 为什么我不能将引用作为 std::async 的函数参数传递
- 我可以将向量作为initial_sum和不同的函数传递给 std::累积吗?
- 如何使用 std::string 作为 QHash 的键?
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 传递 std::数组变量作为参数
- std::string 可以作为 nlohmann::json 传递给显式构造函数
- 是否可以使用 std::array 作为 POD 结构的数据容器?
- 附加使用 Struct 作为"multikey"并将 std::vector 用作映射值的映射
- std::p作为 std 中定义的unordered_map自定义键的字符串的空气失败并出现模板错误
- 我想从这段代码中删除使用命名空间std,但我不确定什么都需要用std::作为前缀