包含向量的迭代器的无序列图 - 迭代器不可取消引用C++
Unordered map containing an Iterator to a Vector - Iterator not Dereferencable C++
我有一个无序映射,它将字符串存储为其键,并将向量中某个点的迭代器存储为其数据。向量中的每个元素都包含一个字符串和一个 int(字符串出现的次数)。我已经编写了一个 increaseCount(std::string, int) 函数,该函数应该将新字符串插入无序映射中,除非它已经在容器中。如果是这种情况,函数应该在无序映射中找到键,到达迭代器指向的向量中的相应位置,并向向量元素的 int 参数添加一个。但是,在执行第二种情况时,会出现错误"矢量迭代器不可取消引用"。这是我编写的代码。
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;
}
}
我知道这意味着迭代器指向内存中的空位置,但我无法弄清楚它在哪里失去了对目的地的跟踪。
这段代码不起作用的原因是 vector::p ush_back 使迭代器无效,也就是说,如果您通过添加新元素使向量变大,您对大小为 3 的向量的迭代器可能无法工作。来自 cpp首选项:如果新的 size() 大于 capacity(),则所有迭代器和引用(包括过去结束的迭代器)都将失效。否则,只有过去结束迭代器失效。
您当然可以提前为向量保留足够的空间,这样迭代器就不会失效,但作为一般规则,您最好使用数字索引。
相关文章:
- 为什么范围算法与 std 的迭代器不兼容?
- 矢量迭代器不能与 std::shared_ptr<> 取消引用
- forward_list迭代器不兼容
- 向量迭代器不兼容的错误,用于保存另一个向量的迭代器的向量
- C++,弹出调试断言失败窗口,我得到矢量迭代器不兼容的错误运行时
- f.getline() 迭代器不增加
- 当我发生碰撞检测时,矢量迭代器不兼容
- 为什么C++字符串迭代器不检查错误?
- debug断言矢量迭代器不可用find_if删除
- 为什么标准容器迭代器不会重载"->*"?
- 为什么反向迭代器不是 C++17 标准下的正式迭代器类别?
- C XTREE崩溃在出口上,映射/设置迭代器不可用
- C++:为什么输出迭代器不支持比较操作?
- 迭代器不兼容错误
- C++向量迭代器不是增量的
- 为什么更多的迭代器不是随机访问?
- 为什么迭代器不返回集合的开头
- 字符串迭代器不兼容错误,当我将字符串转换为矢量<byte>时
- 迭代器不能被另一个相同大小的向量重用吗?
- 字符串迭代器不可用C 问题