列表迭代器不可取消引用
List iterator not dereferencable
所以我正在编写这个道路网络类。它包含一个地图,用于保持顶点和一组连接到它的顶点。
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
迭代器并取消引用,这是未定义的行为。
相关文章:
- C++取消引用指针.为什么会发生变化
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 取消引用运算符不能重载
- 了解通过引用传递取消引用指针时C++堆/堆栈分配
- 对于实际指针类型,用于检测类似指针(可取消引用)类型的模板函数失败
- 升压::可选<bool>取消引用
- C++如何将类方法传递给要求引用可调用的函数
- 结构引用和取消引用运算符
- 使用引用和取消引用运算符读取代码行时遇到问题
- 如何确定类型在 C++03 中是否可取消引用
- 我们应该在通过引用之前取消引用指针吗
- 数组迭代器不是可取消引用的错误
- 取消引用指向取消引用类中的函子的指针
- C++/CLI 项目如何引用可移植类库
- 如何在 boost::asio 线程池中使任务可取消/可中断
- 迭代器不是可取消引用的堆栈(表达式树)和循环无法正常工作
- 如何使用boost::expression-static在语义操作中引用可选子匹配
- 何时引用和取消引用具有成员函数的指针
- 列出迭代器而不是可取消引用的运行时
- 为什么持有引用可复制的类