【问题标题】:Unordered map containing an Iterator to a Vector - Iterator not Dereferencable C++包含指向向量的迭代器的无序映射 - 迭代器不可取消引用 C++
【发布时间】:2015-01-23 13:56:45
【问题描述】:

我有一个无序映射,它存储一个字符串作为其键,并将一个迭代器存储到向量中的某个点作为其数据。向量中的每个元素都包含一个字符串和一个 int(字符串出现的次数)。我编写了一个 increaseCount(std::string, int) 函数,它应该将新字符串插入到无序映射中,除非它已经在容器中。如果是这种情况,该函数应该在无序映射中找到键,到达迭代器指向的向量中的相应位置,并将向量元素的 int 参数加一。但是,在执行第二种情况时,会出现错误“Vector iterator not dereferencable”。这是我编写的代码。

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),迭代器都会失效,因此不再指向有效的内存位置。
  • 好的,我会试一试。我可以将索引实现为与向量中的点相对应的 int 吗?谢谢!

标签: c++ vector iterator unordered-map


【解决方案1】:

此代码不起作用的原因是 vector::push_back 使迭代器无效,也就是说,如果您通过添加新元素使向量变大,则您对大小为 3 的向量的迭代器可能无法工作.来自 cppreference:如果新的 size() 大于 capacity() 则所有迭代器和引用(包括过去的迭代器)都将失效。否则只有过去的迭代器无效。

你当然可以提前为向量保留足够的空间,这样迭代器就不会失效,但作为一般规则,你最好使用数字索引。

【讨论】:

  • 有没有办法通过为向量声明更大的尺寸来解决这个问题?例如,我知道我的向量将始终小于或等于 x 个项目,因此使向量 x * 2。
  • @red_student 如答案所述,您可以使用vec.reserve(x) 确保capacity() 至少为x,从而防止重新分配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 2016-01-17
相关资源
最近更新 更多