我有一個無序的映射,存儲一個字符串作爲它的鍵和一個迭代器到一個向量中的一個點作爲它的數據。向量中的每個元素都包含一個字符串和一個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;
}
}
我知道,這意味着迭代器指向內存中的空位置,但我想不通的地方失去跟蹤它的目的地。
您應該將索引存儲在向量中,而不是迭代器。任何時候矢量調整大小(例如從push_back),迭代器都會失效,因此不再指向有效的內存位置。 – Borgleader 2014-11-25 14:07:36
好吧,我會放棄這一點。我可以將索引作爲與向量中的點對應的int嗎?謝謝! – 2014-11-25 14:17:57