访问作为向量索引的列表中的每个节点

Accessing Each Node in a list that is an index in a vector

我目前正在使用私有数据成员 vector<list<pair<K, V>>> hashTable; 进行散列 table。

我需要访问每个列表,然后访问每个列表以实现各种不同的功能。我目前正在这样做:

for(int i = 0; i < hashTable.capacity(); i++){
        list<pair<K,V>>* listPtr = hashTable[i];
for(pair<K,V>* pairPtr = listPtr->front(); pairPtr != listPtr->end(); pairPtr++){
                pair<K,V> tempPair;
                tempPair.first = pairPtr->first;
                tempPair.second = pairPtr->second;
                insert(tempPair);
            }
        }
}

上面的代码是我的 rehash 函数的一部分。插入基于散列函数插入对,散列函数基于向量的大小进行散列。这并不重要。我只想知道如何到达每个列表,然后是每对。

我的问题是,有没有更好的方法来访问向量中的每个列表和对?

访问每个列表中每对的简单方法是

for (const auto& list : hashTable)
{
    for (const auto& pair : list)
    {
        ...
    }
}

但是上面代码中的 insert 函数让我担心。如果您在同时修改 vectors/lists 的同时对其进行迭代,那么事情就会发生变化。