使用 struct 作为 hashmap 中的键。如何插入值?
代码在编译行失败
map_free_segments [ loc ] = color;
错误的第一行是:
错误 C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' :无法推导 'const std: 的模板参数: :向量<_Ty,_Alloc> &'来自“const localization”
完整来源:
#include <windows.h>
#include <hash_map>
using namespace std;
using namespace stdext;
#pragma pack(1)
struct localization
{
char X;
char Y;
char Z;
char L;
};
#pragma pack(1)
typedef hash_map<localization,unsigned long> type_map_free_segments;
//typedef pair<localization, unsigned long> pair_loc;
int main(int argc, CHAR* argv[])
{
unsigned long color = 1234;
type_map_free_segments map_free_segments;
localization loc;
loc.X = 1;
loc.Y = 2;
loc.Z = 3;
loc.L = 5;
map_free_segments [ loc ] = color;
//map_free_segments.insert( pair_loc(loc, color ));
return 0;
}
The code fail at compilation line
map_free_segments [ loc ] = color;
The first line for the errors is :
error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'const localization'
The complete source :
#include <windows.h>
#include <hash_map>
using namespace std;
using namespace stdext;
#pragma pack(1)
struct localization
{
char X;
char Y;
char Z;
char L;
};
#pragma pack(1)
typedef hash_map<localization,unsigned long> type_map_free_segments;
//typedef pair<localization, unsigned long> pair_loc;
int main(int argc, CHAR* argv[])
{
unsigned long color = 1234;
type_map_free_segments map_free_segments;
localization loc;
loc.X = 1;
loc.Y = 2;
loc.Z = 3;
loc.L = 5;
map_free_segments [ loc ] = color;
//map_free_segments.insert( pair_loc(loc, color ));
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要使用复杂的结构/类作为 hash_map 中的键,您需要提供一个实现来告诉容器如何比较两个键。
您的结构需要实现 <操作员来做到这一点。
您可能还需要定义一个 hash_comp 函数来根据结构的值计算哈希值。
有关详细信息,请参阅 hash_compare 类的帮助。
To use a complex struct/class as the key in a hash_map, you need to provide an implementation that tells the container how to compare two keys.
Your struct needs to implement the < operator to do that.
You might also need to define a hash_comp function to compute hashes based off of your struct's values.
Look at the help for the hash_compare class for more information.