简体   繁体   English

Boost unordered_map是否仅可用于将项目与整数相关联?

[英]Does the Boost unordered_map only work to associate items with integers?

I had a 我曾有一个

HashMap<Node, Double> 

in Java which I'd use later on to retrieve the double associated with a node. 在Java中,稍后将使用它来检索与节点关联的双精度型。 I've tried to do 我试着做

boost::unordered_map<Node*, double> 

but I get a "error C2108: subscript is not of integral type" when I try to put something in it, like: 但是当我尝试在其中添加某些内容时,出现“错误C2108:下标不是整数类型”:

map[some_node] = some_double;

If I interpreted the error right, then I have to replace my double with an int. 如果我正确地解释了错误,那么我必须将我的double替换为int。 Is there a simple way around this? 有没有解决这个问题的简单方法?

okay, here's the function then: 好的,这是函数:

void myClass::someFunction(const double* r)
{
    //map is boost::unordered_map<Node*, double> 
    //nodes is a pointer to std::vector<Node*>
    std::vector<Node*>::iterator it;
    for(it = nodes->begin(); it != nodes->end(); it++)
    {
        //calculate the index
        map[*it] = r[index]; //error
    }
}

The error is not for the map access, but for r[index] . 错误不是针对地图访问,而是针对r[index] index must be an integer type. index必须是整数类型。

Unlike Java, C++ does not provide hashing functions for classes. 与Java不同,C ++不为类提供哈希函数。 If the type of the hashmap key is an integer or a pointer, then C++ can use the fact that an integer is its own hash, but it can't fo this for types you define yourself - in that case you have to provide a hash function explicitly. 如果hashmap键的类型是整数或指针,则C ++可以使用整数是其自身的哈希值这一事实,但对于您自己定义的类型,则不能这样做-在这种情况下,您必须提供哈希值明确地起作用。 This can be hard to do efficiently, which is one reason that hashes were excluded from the original C++ standard in favour of maps that use a tree structure rather than a hash table, and only require operator<() to be defined, which is usually much easier to write than an efficient hash function. 这可能很难高效地完成,这是哈希从原始C ++标准中排除的原因之一,而是使用树结构而不是哈希表的映射,而只需要定义operator <(),这通常是比高效的哈希函数更容易编写。

I'd also observe that if you are using a pointer to a node as the hash key, it may be easier and quicker to store the double value in the node itself, rather than use a hashtable, as you effectively already have the node you want to hand. 我还将观察到,如果您使用指向节点的指针作为哈希键,则将双精度值存储在节点本身中可能会比使用哈希表更容易,更快捷,因为您实际上已经拥有该节点了想牵手。

It's not complaining about the double, it's complaining about "some_node". 它不是在抱怨双重,而是在抱怨“ some_node”。

What is your map defined as specifically? 您的地图具体定义了什么?

You don't give the declaration of some_node but you would get this error if some_node is not a pointer. 您没有给出some_node的声明,但是如果some_node不是指针,则会出现此错误。 The double should be fine. 两倍应该可以。

So you might need something like this: 因此,您可能需要以下内容:

Node some_node;
...
map[&some_node] = some_double; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM