問題描述
背景:我來自 Java 世界,我對 C++ 或 Qt 相當陌生.
Background: I am comming from the Java world and I am fairly new to C++ or Qt.
為了玩轉unordered_map,我編寫了以下簡單程序:
In order to play with unordered_map, I have written the following simple program:
#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();
}
不幸的是,我遇到了以下沒有啟發性的錯誤.甚至連行號都沒有.
Unfortunately, I am running into the folowing error which isn't inspiring. There is not even a line number.
:-1: 錯誤: collect2: ld 返回 1 個退出狀態
:-1: error: collect2: ld returned 1 exit status
知道問題的根源嗎?
推薦答案
§23.2.5,第 3 段,說:
§23.2.5, paragraph 3, says:
每個無序關聯容器由 Key
參數化,通過滿足 Hash 要求(17.6.3.4)的函數對象類型 Hash
并充當參數的哈希函數Key
類型的值,并通過一個二元謂詞 Pred
誘導 Key
類型的值的等價關系.
Each unordered associative container is parameterized by
Key
, by a function object typeHash
that meets the Hash requirements (17.6.3.4) and acts as a hash function for argument values of typeKey
, and by a binary predicatePred
that induces an equivalence relation on values of typeKey
.
使用 vector
作為 Key
并且不提供明確的哈希和等價謂詞類型意味著默認的 std::hash
和 std::equal_to
將被使用.
Using vector<float>
as Key
and not providing explicit hash and equivalence predicate types means the default std::hash<vector<float>>
and std::equal_to<vector<float>>
will be used.
等價關系的std::equal_to
很好,因為向量有一個運算符==
,這就是std::equal_to
使用.
The std::equal_to
for the equivalence relation is fine, because there is an operator ==
for vectors, and that's what std::equal_to
uses.
然而,沒有 std::hash<vector<float>>
特化,這可能就是你沒有向我們展示的鏈接器錯誤所說的.您需要提供自己的哈希器才能使其正常工作.
There is however, no std::hash<vector<float>>
specialization, and that's probably what the linker error you didn't show us says. You need to provide your own hasher for this to work.
編寫這種散列器的一種簡單方法是使用 boost::hash_range
:
An easy way of writing such an hasher is to use 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;
當然,如果您需要在映射中使用不同的相等語義,則需要適當地定義散列和等價關系.
Of course, if you need different equality semantics in the map you need to define the hash and equivalence relation appropriately.
1.但是,在對無序容器進行散列時要避免這種情況,因為不同的順序會產生不同的散列值,并且無法保證無序容器中的順序.
這篇關于C++ unordered_map 在使用向量作為鍵時失敗的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!