2014-11-25 82 views
1

我有一個無序的映射,存儲一個字符串作爲它的鍵和一個迭代器到一個向量中的一個點作爲它的數據。向量中的每個元素都包含一個字符串和一個int(字符串出現的次數)。我編寫了一個increaseCount(std :: string,int)函數,該函數應該將新字符串插入到無序映射中,除非它已經在容器中。如果是這種情況,函數應該在無序映射中找到關鍵字,到達迭代器指向的向量中的相應位置,並向vector元素的int參數中添加一個。但是,執行第二種情況時,出現錯誤「Vector iterator not derefereenable」。這是我編碼的。無序的映射包含一個迭代器到一個向量 - 迭代器不可忽略的C++

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; 

} 

}

我知道,這意味着迭代器指向內存中的空位置,但我想不通的地方失去跟蹤它的目的地。

+2

您應該將索引存儲在向量中,而不是迭代器。任何時候矢量調整大小(例如從push_back),迭代器都會失效,因此不再指向有效的內存位置。 – Borgleader 2014-11-25 14:07:36

+0

好吧,我會放棄這一點。我可以將索引作爲與向量中的點對應的int嗎?謝謝! – 2014-11-25 14:17:57

回答

2

此代碼無法正常工作的原因是vector :: push_back使迭代器無效,即對於大小爲3的矢量而言,您可能無法使用迭代器,如果通過添加新的元件。從cppreference:如果新的size()大於capacity(),那麼所有迭代器和引用(包括過去末端迭代器)都將失效。否則只有最後一個迭代器失效。

您當然可以提前爲矢量預留足夠的空間,以便迭代器不會失效,但作爲一般規則,最好使用數字索引。

+0

有沒有辦法解決這個問題,通過聲明一個更大的矢量開始?例如,我知道我的向量總是小於或等於x項目,因此請按照答案中的說明製作向量x * 2. – 2014-11-25 14:50:17

+1

@red_student,可以使用'vec.reserve(x)'確保' capacity()'至少是'x',因此阻止了重新分配。 – 2014-11-25 20:37:07