xpirad xpirad - 13 days ago 9
C++ Question

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!

Answer

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.