繁体   English   中英

C ++分段错误,push_back在列表中,但不在矢量上

[英]C++ Segmentation fault with push_back on list but not on vector

我们正在使用带有链接示例的类的哈希表。 我使用STL将哈希表定义为std::vector<std::list< Pair > > mTable 不幸的是,当我在mTable [index]上调用push_back时,出现了段错误。 如果我将mTable定义为std::vector<std::vector< Pair > > mTable. 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
}

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM