[英]How do I insert into boost::unordered_set<boost::unordered_set<int> >?
以下代碼無法編譯,但如果我刪除注釋行,它會編譯並正確運行。 我只打算使用 boost,因為 C++ 默認不為std::unordered_set<int>
提供 hash function 。
#include <iostream>
#include <boost/unordered_set.hpp>
int main() {
boost::unordered_set<boost::unordered_set<int> > fam;
boost::unordered_set<int> s;
s.insert(5);
s.insert(6);
s.insert(7);
std::cout << s.size() << std::endl;
fam.insert(s); // this is the line causing the problem
return 0;
}
編輯1:
我想比我在 OP 中更清楚。 首先我知道boost::unordered_set<>
的想法是它是用 hash 表而不是 BST 實現的。 我知道任何要成為boost::unordered_set<>
的模板類型的東西都需要提供 hash function 和平等 ZC1C425268E68385D1AB5074C17A94F14。 我也知道默認情況下std::unordered_set<>
沒有定義 hash function ,這就是以下代碼無法編譯的原因:
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<std::unordered_set<int> > fam;
return 0;
}
但是,我認為 boost 為其所有容器提供了 hash 函數,這就是為什么我相信以下代碼可以編譯的原因:
#include <iostream>
#include <boost/unordered_set.hpp>
int main() {
boost::unordered_set<boost::unordered_set<int> > fam;
return 0;
}
所以現在,我不確定為什么上面的 boost 代碼可以編譯,但 OP 中的代碼卻沒有。 我錯了 boost 為其所有容器提供 hash function 嗎? 我真的很想避免定義一個新的 hash function,尤其是當我的實際預期用途是擁有更復雜的數據結構時: boost::unordered_map<std::pair<boost::unordered_map<int, int>, boost::unordered_map<int, int> >, int>
。 看來這應該是一個我不必定義自己的已解決問題,因為 IIRC python 可以處理成套集合沒問題。
unordered_set
(或_map
)使用hashing ,並且需要為其元素定義 hash 運算符。 沒有為boost::unordered_set<int>
定義 hash 運算符,因此它不能將這種類型的元素放入您的集合中。
您可以為此編寫自己的 hash function。 例如,這是一種典型的通用 hash 方法,盡管您可能希望針對您的特定數據對其進行自定義。 如果將此代碼放入示例中,它應該可以工作:
namespace boost {
std::size_t hash_value(boost::unordered_set<int> const& arg) {
std::size_t hashCode = 1;
for (int e : arg)
hashCode = 31 * hashCode + hash<int>{}(e);
return hashCode;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.