我试图宣布一个priority_queue:
std::priority_queue<int, std::vector<int>, std::function<bool(int, int)>> m_openList;
以及我用来初始化它的方式是:
m_openList = std::priority_queue<int, std::vector<int>, std::function<bool(int,int)>>(keyCompare);
keyCompare是一个函数:
bool PathPlanManager::keyCompare(int pointer1, int pointer2) {
return m_mapNode[pointer1] > m_mapNode[pointer2];}
但似乎错了。顺便说一句,我该如何清除这个priority_queue?
尝试之后,我的代码是这样的:
class PathPlanManager {
public:
class KeyCompare {
public:
KeyCompare(PathPlanManager& manager) : m_manager(&manager){}
bool operator() (int pointer1, int pointer2) {
return m_manager->m_nodeMap[pointer1] < m_manager->m_nodeMap[pointer2];
}
private:
PathPlanManager* m_manager;
};
void init() {
m_nodeMap.resize(100);
for (int i = 0; i < 100; i++) {
m_nodeMap[i] = 100 - i;
}
m_openList = std::priority_queue<int, std::vector<int>, KeyCompare>();
}
private:
vector<int> m_nodeMap;
std::priority_queue<int, std::vector<int>, KeyCompare> m_openList;
};
当我尝试构建它时,有一个错误说没有匹配的构造函数用于初始化&#39; value_compare&#39;(又名&#39; PathPlanManager :: KeyCompare&#39;)
答案 0 :(得分:0)
KeyCompare
需要PathPlanManager
的对象:
class PathPlanManager {
public:
class KeyCompare {
public:
KeyCompare(PathPlanManager& manager) : m_manager(&manager) { }
bool operator()(int pointer1, int pointer2) {
return m_manager->m_mapNode[pointer1] > m_manager->m_mapNode[pointer2];
}
private:
PathPlanManager* m_manager;
};
private:
std::vector<int> m_mapNode;
typedef std::priority_queue<int, std::vector<int>, KeyCompare> mypq_type;
mypq_type m_openList;
}
使用示例:
PathPlanManager mgr; // somewhere this is initialised
...
// want to sort some entries according to mgr
std::vector<int> entries{ 0, 13, 37, 42 };
std::sort(entries.begin(), entries.end(), PathPlanManager::KeyCompare(mgr));
// now entries is sorted according to mgr
看到您的更新后:如果您想将priority_map
用作课程成员(我们称之为Planner
),您可以这样做:
class Planner {
public:
Planner(PathPlanManager& mgr);
private:
std::priority_queue<int, std::vector<int>, PathPlanManager::KeyCompare> m_openList;
}
Planner::Planner(PathPlanManager& mgr)
: m_openList(PathPlanManager::KeyCompare(mgr))
{ }
// Usage:
...
PathPlanManager mgr;
Planner planner(mgr);
...