为何简化示例未触发vector iterators incompatible错误,项目中却出现?
为什么Visual C++会触发"vector iterators incompatible"错误?
运行正常的简化示例代码
#include <iostream> #include <algorithm> #include <vector> typedef std::pair<int, int> pos; int main() { std::vector<pos>::iterator it; std::vector<pos> s; s.push_back({10, 20}); s.push_back({11, 30}); std::vector<pos> target = {{10, 20}, {11, 30},{141, 340}, {151, 340}}; for (pos i: s) { it = std::find(target.begin(), target.end(), i); } if (it != target.end()) std::cout << "Element found in myvector: " << it->first << '\n'; else std::cout << "Element not found in myvector\n"; return 0; }
触发错误的项目代码
typedef std::pair<int, int> pos; std::vector<pos> monsters; bool Game::isMonsterOnPathToTreasure() { avoidMonsterPath = false; std::vector<pos> monsterPath; getShortestPath(treasurePos, monsterPath); std::vector<pos>::iterator it; for (pos monster: monsters) { it = std::find(monsterPath.begin(), monsterPath.end(), monster); } if (it != monsters.end()) { return true; } return false; }
错误原因分析
- 迭代器跨容器比较:项目代码中,
it被赋值为monsterPath容器的迭代器,但最后判断时却和monsters.end()(来自另一个完全不同的vector容器)做比较。Visual C++的迭代器调试机制会严格检查这种非法操作,直接抛出vector iterators incompatible错误——迭代器只能和同一容器的迭代器进行比较。 - 逻辑冗余且错误:循环结束后
it仅保留最后一次std::find的结果,哪怕前面有匹配成功的元素也会被覆盖;就算最后一次find命中,用monsterPath的迭代器和monsters的end()比较本身毫无意义。
修复后的代码示例
bool Game::isMonsterOnPathToTreasure() { avoidMonsterPath = false; std::vector<pos> monsterPath; getShortestPath(treasurePos, monsterPath); // 遍历怪物,找到第一个在路径上的就直接返回true for (const pos& monster : monsters) { auto it = std::find(monsterPath.begin(), monsterPath.end(), monster); if (it != monsterPath.end()) { // 同一容器的迭代器合法比较 return true; } } return false; }
内容的提问来源于stack exchange,提问作者Fox1942
相关产品推荐
相关产品推荐

