简体   繁体   中英

List iterator not dereferencable

So l'm writing this road network class.It contains a map which is used to keep a vertex and a set of vertexes which is connected to 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);
}
};

It compiled.but whenever i tried to use the function addedge,the program would throw a runtime error:List iterator not dereferencable?

Can someone tell me what's wrong with this code? Thanks in advance!

You should check the result of find before dereferencing it:

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

If find cannot find the element it returns the end iterator and dereferencing that is undefined behavior.

You dereference the iterator result of find() without testing for a valid result. Change your code doing like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM