列表迭代器不可取消引用

List iterator not dereferencable

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

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);
}
};

它 compiled.but 每当我尝试使用函数 addedge 时,程序会抛出运行时 error:List 迭代器不可取消引用?

有人能告诉我这段代码有什么问题吗?提前致谢!

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

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

如果 find 找不到元素,它 returns 迭代器和取消引用是未定义的行为。

您在未测试有效结果的情况下取消引用 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);
      }