[英]C++ How to insert array to unordered_map as its key?
嗨,我曾經有一個unordered_set來保存我的16個int數組,現在我需要再存儲一個int作為其存儲桶。 我想知道是否可以將數組插入到unordered_set中,還是可以使用以前使用的模板?
#include <unordered_set>
#include <array>
namespace std
{
template<typename T, size_t N>
struct hash<array<T, N> >
{
typedef array<T, N> argument_type;
typedef size_t result_type;
result_type operator()(const argument_type& a) const
{
hash<T> hasher;
result_type h = 0;
for (result_type i = 0; i < N; ++i)
{
h = h * 31 + hasher(a[i]);
}
return h;
}
};
}
std::unordered_set<std::array<int, 16> > closelist;
int main()
{
std::array<int, 16> sn = {1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15};
closelist.insert(sn);
}
我可以將其更改為此嗎?
std::unordered_map<std::array<int, 16>,int > closelist;
int main()
{
std::array<int, 16> sn = {1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15};
closelist.insert(sn,24);
}
而且我聽不懂模板,不知道什么是“ h = h * 31 + hasher(a [i]);”?
謝謝!!!
我可以將其更改為此嗎?
首先,您的數組初始化錯誤:
std::array<int, 16> sn = {{1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15}};
// ^ ^
由於std::array
沒有以std::initializer_list
作為參數的構造函數。 因此,第一層用於初始化對象,第二層用於初始化對象中的數組。
其次,從參考 :
std::pair<iterator,bool> insert( const value_type& value ); template <class P> std::pair<iterator,bool> insert( P&& value );
因此,您應該傳遞std::pair
(或其他可以轉換為std::pair
東西),例如:
closelist.insert({sn,24});
或者,更簡單:
closelist[sn] = 24;
如何將任何對象用作鍵:
缺點是您可能需要以某種方式解決沖突。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.