2012-05-01 22 views
9

背景:我从Java世界来到,而我对C++或Qt相当陌生。C++ unordered_map与矢量作为键一起使用时失败

为了与unordered_map玩,我已经写了下面的程序:

#include <QtCore/QCoreApplication> 
#include <QtCore> 
#include <iostream> 
#include <stdio.h> 
#include <string> 
#include <unordered_map> 

using std::string; 
using std::cout; 
using std::endl; 
typedef std::vector<float> floatVector; 

int main(int argc, char *argv[]) { 
    QCoreApplication a(argc, argv); 

    floatVector c(10); 
    floatVector b(10); 

    for (int i = 0; i < 10; i++) { 
     c[i] = i + 1; 
     b[i] = i * 2; 
    } 

    std::unordered_map<floatVector, int> map; 

    map[b] = 135; 
    map[c] = 40; 
    map[c] = 32; 

    std::cout << "b -> " << map[b] << std::endl; 
    std::cout << "c -> " << map[c] << std::endl; 
    std::cout << "Contains? -> " << map.size() << std::endl; 

    return a.exec(); 
} 

不幸的是,我遇到了如下因素的错误是不令人振奋。甚至没有行号。

:-1: error: collect2: ld returned 1 exit status

任何想法的问题来源?

在此先感谢。

+1

你需要一个散列函数,它需要一个'vector ' –

+2

这不是运行时失败。 –

+0

@SethCarnegie这就是我虽然也遇到了问题。但是,在我看来,像vector这样基本的类应该有一个默认的散列函数。如果情况并非如此,你能否向我解释如何提供或向我提供某些材料。谢谢! –

回答

21

§23.2.5,第3款,说:

Each unordered associative container is parameterized by Key , by a function object type Hash that meets the Hash requirements (17.6.3.4) and acts as a hash function for argument values of type Key , and by a binary predicate Pred that induces an equivalence relation on values of type Key .

使用vector<float>Key,而不是提供明确的哈希和等价的谓词类型意味着默认std::hash<vector<float>>std::equal_to<vector<float>>将被使用。

等效关系的std::equal_to是好的,因为有一个运营商==矢量,这就是std::equal_to使用什么。

然而,没有std::hash<vector<float>>专业化,这可能是你没有告诉我们的链接器错误说。你需要提供你自己的哈希器才能工作。

写这样的散列器的一个简单的方法是使用boost::hash_range

template <typename Container> // we can make this generic for any container [1] 
struct container_hash { 
    std::size_t operator()(Container const& c) const { 
     return boost::hash_range(c.begin(), c.end()); 
    } 
}; 

然后你可以使用:

std::unordered_map<floatVector, int, container_hash<floaVector>> map; 

当然,如果你在你需要的地图需要不同的平等语义适当地定义哈希和等价关系。


1。然而,这避免对散列无序容器,不同的次序会产生不同的散列,并且在无序容器的顺序不被保证。

+1

非常感谢你的确解决了我的问题。 请注意人们会有相同的问题: 使用boost :: hash_range你需要#include

+0

@ user1162647:这实际上是该文档页面上的第一件事。 ; - ] – ildjarn

+0

@R。Martinho Fernandes:如果你还在观看,该页面上的文档会说:“hash_range对元素的顺序非常敏感,所以不适合在无序容器中使用它。”这是否表明上述用法是错误的? – ForeverLearning

相关问题