C ++分段错误与列表上的push_back但不在向量上

时间:2017-11-01 13:42:11

标签: c++ list vector stl

我们正在使用类的链接示例来执行哈希表。使用STL我将哈希表定义为std::vector<std::list< Pair > > mTable。不幸的是,当我在mTable [index]上调用push_back时,我得到一个seg错误。如果我将mTable定义为std::vector<std::vector< Pair > > mTable.,则该错误不存在 我使用列表不正确吗?这是代码:

template<class K, class V>
class HashTable {
    private:
        class Pair {
            public:
                K mKey;
                V mVal;
        };
        std::vector<std::list<Pair> > mTable;
...
};

...

template<class K, class V>
HashTable<K, V>::HashTable(const int size) {
    mTable.reserve(size);
}

template<class K, class V>
bool HashTable<K, V>::insert(const K &key, const V &val) {
    int size = mTable.capacity(); // Gets how many elements can be stored in the array/vector.
    int index = hashcode(key); // convert the key to an integer.
    index %= size; // Size down the 'size' variable so it index into the array/vector.
    Pair toInsert;
    toInsert.mKey = key;
    toInsert.mVal = val;
    std::cout << mTable[index].size() << "\n"; // works fine.
    mTable[index].push_back(toInsert); // (SEG FAULT) Adds value to the hash table
}

1 个答案:

答案 0 :(得分:0)

试试这个:

HashTable<K, V>::HashTable(const int size):mTable(size,std::list<Pair>){
}