2014-11-25 69 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