所以我在写这个道路网络类,它包含一个用于保留顶点的地图和一组与其相连的顶点。
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句