列表迭代器不可取消引用

List iterator not dereferencable

本文关键字:引用 可取消 不可取 迭代器 列表      更新时间:2023-10-16

所以我正在编写这个道路网络类。它包含一个地图,用于保持顶点和一组连接到它的顶点。

struct vertex {
double lat;  //latitude
double longit;  //longitude
vertex(double lat, double longit) :lat(lat), longit(longit) {}
};
struct hash_vertex { //hash function for map and set
unsigned operator()(const vertex& v) const {
string s(to_string(v.lat) + to_string(v.longit));
hash<string> hash;
return hash(s);
}
};
struct equal_vertex {  //equal function for map and set
bool operator()(const vertex &v1, const vertex &v2) const {
return abs(v1.lat - v2.lat) + abs(v1.longit - v2.longit) < error;
}
};
class road_network {
private:
unordered_map<vertex, unordered_set<vertex,hash_vertex,equal_vertex>, hash_vertex, equal_vertex> road;
public:
void addedge(const vertex &u, const vertex &v) {
auto it = *road.find(u);
auto it2 = *road.find(v);
it.second.insert(v);
it2.second.insert(u);
}
};

但是每当我尝试使用函数 addge 时,程序都会抛出一个运行时错误:列表迭代器不是可取消引用的?

有人可以告诉我这段代码有什么问题吗?提前感谢!

取消引用find()的迭代器结果,而不测试有效结果。像这样更改代码:

auto it = road.find(u);
auto it2 = road.find(v);
if(it != road.end() && it2 != road.end()) {
it->second.insert(v);
it2->second.insert(u);
}

在取消引用之前,您应该检查find的结果:

auto it = road.find(u);
if (it != road.end()) {  auto x = *it;}

如果find找不到该元素,它将返回end迭代器并取消引用,这是未定义的行为。