简体   繁体   中英

Unordered map containing an Iterator to a Vector - Iterator not Dereferencable C++

I have an unordered map that stores a string as its key and an iterator to a spot in a vector as its data. Each element in the vector holds a string and an int (number of times the string appears). I have coded an increaseCount(std::string, int) function that is supposed to insert the new string into the unordered map, unless it is already within the container. If this is the case, the function should find the key in the unordered map, got to the corresponding location in the vector that the iterator points to, and add one to the int parameter of the vector element. However, when executing the second case, the error "Vector iterator not dereferencable" shows up. Here is what I have coded.

void ourTrends::increaseCount(std::string s, unsigned int amount){
// check to see if key is already in
if(wordStoreTable.find(s) == wordStoreTable.end()){
    // add the element into the hash table
    std::vector<std::pair<std::string, int>>::iterator it;
    std::pair<std::string, std::vector<std::pair<std::string, int>>::iterator> word (s, it);
    wordStoreTable.insert(word);

    // add element to back of vector
    std::pair<std::string, int> p1 (s, amount);
    sortedVector.push_back(p1);
    //std::swap(sortedVector.front(), sortedVector.back());
    // set the iterator of the hash pair to the end of the current vector size
    it = sortedVector.end();
    --it;
    wordStoreTable.find(s)->second = it;
    isSorted = false;

} else{
    int x = wordStoreTable.find(s)->second->second;
    std::pair<std::string, int> p1 (s, x + amount);
    sortedVector.erase(wordStoreTable.find(s)->second);
    sortedVector.push_back(p1);
    //std::swap(sortedVector.begin(), sortedVector.end());
    std::vector<std::pair<std::string, int>>::iterator it = sortedVector.end();
    --it;
    wordStoreTable.find(s)->second = it;
    std::cout << wordStoreTable.find(s)->first << std::endl;

}

}

I know that this means the iterator is pointing to an empty location in memory, but I cannot figure out where it loses track of its destination.

The reason this code doesn't work, is that vector::push_back invalidates the iterators, that is, an iterator you had for a vector of size 3, might not work if you make the vector larger by adding a new element. From cppreference: If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

You certainly could reserve enough space for the vector ahead of time, so that iterators do not invalidate, but as a general rule, you're better off with using numerical indices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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