我想創建一個開放的哈希表。我想使用一個串列陣列,其中陣列的大小是一個模板引數,但問題是我不知道如何將分配器傳遞給所有串列實體,而且我不能使用向量,因為我將需要另一個分配器進行串列分配(alloception),有沒有辦法用相同的值初始化整個串列陣列?我知道我可以這樣初始化list<int> mylist[] = {{allocator}, {allocator}, {allocator}}
但這個想法是將大小作為模板變數。例子:
template<typename KEY, typename VAL, typename ALLOC=std::allocator<struct _internal>, size_t TBL_SIZE=100>
class open_hash_table{
private:
std::list<struct _internal, ALLOC=ALLOC> _table[TBL_SIZE];
public:
open_hash_table(ALLOC allocator=ALLOC())
:_table({allocator, allocator ... allocator}){}
};
ps 我的編譯器最高支持 c 11
uj5u.com熱心網友回復:
這使用 C 14std::make_index_sequence并生成它,但您可以按照此處std::index_sequence所示進行自己的實作。使用委托建構式,您可以添加另一個接受 an 的建構式,然后您可以擴展序列并獲取可變引數串列,例如index_sequence
template<typename KEY, typename VAL, typename ALLOC=std::allocator<struct _internal>, size_t TBL_SIZE=100>
class open_hash_table{
private:
std::list<struct _internal, ALLOC> _table[TBL_SIZE];
template <std::size_t... Is>
open_hash_table(ALLOC allocator, std::index_sequence<Is...>)
: _table{ std::list<struct _internal, ALLOC>{((void)Is, allocator)}... } {}
public:
open_hash_table(ALLOC allocator=ALLOC())
: open_hash_table(allocator, std::make_index_sequence<TBL_SIZE>{}) {}
};
您的公共建構式將呼叫私有輔助建構式并傳遞index_sequence其中包含TBL_SIZE多個元素的元素。然后在委托建構式中,該((void)Is, allocator)部分使用逗號運算子來使用 的每個元素,index_sequence但我們將其丟棄,而是讓運算式決議為allocator。(void)Is部分鑄成Is抑制void它未被使用。我們也必須使用std::list<struct _internal, ALLOC>{ ... },因為采用分配器的建構式explicit需要指定型別,不允許隱式轉換。
uj5u.com熱心網友回復:
可以_table通過一些元編程技術直接在成員初始化器串列中進行初始化,但是由于TBL_SIZE的默認值為100,這會使編譯時開銷稍大一些。_table在建構式體中只使用默認構造并初始化其值更合適。
并且由于TBL_SIZE是編譯時常量,而不是使用原始陣列,您可以使用std::array:
template<typename KEY, typename VAL, typename ALLOC=std::allocator<_internal>, size_t TBL_SIZE=100>
class open_hash_table{
private:
std::array<std::list<_internal, ALLOC>, TBL_SIZE> _table;
public:
open_hash_table(ALLOC allocator=ALLOC()) {
_table.fill(std::list<_internal, ALLOC>(allocator));
}
};
此外,由于這是 C ,因此struct關鍵字 instruct _internal是不必要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/440818.html
下一篇:帶有可變引數模板的標準哈希
