继承std::priority_queue实现带find功能的优先队列编译错误排查
问题原因分析
1. 构造函数匹配错误
你自定义的my_priority_queue继承自std::priority_queue,但C++默认不会继承基类的构造函数。你传入lambda比较器初始化队列时,子类没有接收Compare类型参数的构造函数,只有默认生成的拷贝、移动构造函数,因此触发匹配失败的编译错误。
2. find方法逻辑错误
你在遍历底层容器时,直接把迭代器first传给了std::get,迭代器需要解引用才能拿到存储的tuple元素,这行代码会触发后续的编译错误。
解决方案
按以下两点修改你的自定义队列类即可:
- 显式继承父类的所有构造函数
- 修正find方法中迭代器解引用的逻辑
修正后的自定义队列代码
template< class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type> > class my_priority_queue : public std::priority_queue<T, Container, Compare> { public: // 继承父类所有构造函数 using std::priority_queue<T, Container, Compare>::priority_queue; typedef typename std::priority_queue< T, Container, Compare>::container_type::const_iterator const_iterator; const_iterator find(const T& val) const { auto node0 = std::get<2>(val); int node0_depth = std::get<2>(node0); auto first = this->c.cbegin(); auto last = this->c.cend(); while (first!=last) { // 迭代器需要解引用才能拿到存储的元素 auto node1 = std::get<2>(*first); int node1_depth = std::get<2>(node1); if( node0_depth == node1_depth ) return first; ++first; } return last; } };
修改完成后即可正常编译运行。
内容的提问来源于stack exchange,提问作者mkuse
相关产品推荐
相关产品推荐

