我有一个Node Objects的列表容器,它有一个已定义的比较操作(参见头文件)
Node.h
class Node{
private:
int xCoord;
int yCoord;
int value;
double fCost;
double gCost;
double hCost;
Node* parent;
public:
Node();
Node(int x, int y, int value, int cost, Node* parent);
void setParent(Node* parent);
int getX();
int getY();
int getValue();
double getHCost();
double getFCost();
double getGCost();
Node* getParent();
void setHCost(double hCost);
bool operator < (Node& rhs)
{
return fCost < rhs.fCost;
}
};
现在,我将我的列表定义为:
list<Node> openList;
vector<Node> closedList;
Node *start = initiateStart(map);
//openList.push_front(*start);
Node *end;
Node *temp = new Node(1,2,8, 12, start);
temp->setHCost(123.2);
cout << "temp gcost : " << temp->getGCost() <<endl;
cout << "temp hcost : " << temp->getHCost() <<endl;
cout << "temp fcost : " << temp->getFCost() <<endl;
openList.push_front(*temp);
Node *temp2 = new Node(1,2,8, 23, start);
temp2->setHCost(123.2);
cout << "temp2 gcost : " << temp2->getGCost() <<endl;
cout << "temp2 hcost : " << temp2->getHCost() <<endl;
cout << "temp2 fcost : " << temp2->getFCost() <<endl;
openList.push_front(*temp2);
Node *temp3 = new Node(1,2,8, 1, start);
temp3->setHCost(123.2);
cout << "temp3 gcost : " << temp3->getGCost() <<endl;
cout << "temp3 hcost : " << temp3->getHCost() <<endl;
cout << "temp3 fcost : " << temp3->getFCost() <<endl;
openList.push_front(*temp3);
openList.sort();
for (list<Node>::iterator iter = openList.begin(); iter != openList.end(); ++iter){
cout << "iter Fcost : " << iter->getFCost() <<endl;
}
}
现在我的程序打印出来了:
temp gcost : 12
temp hcost : 123.2
temp fcost : 135.2
temp2 gcost : 23
temp2 hcost : 123.2
temp2 fcost : 146.2
temp3 gcost : 1
temp3 hcost : 123.2
temp3 fcost : 124.2
iter Fcost : 124.2
iter Fcost : 146.2
iter Fcost : 135.2
但我期望的结果是:
temp gcost : 12
temp hcost : 123.2
temp fcost : 135.2
temp2 gcost : 23
temp2 hcost : 123.2
temp2 fcost : 146.2
temp3 gcost : 1
temp3 hcost : 123.2
temp3 fcost : 124.2
iter Fcost : 124.2
iter Fcost : 135.2
iter Fcost : 146.2
根据我的阅读,应该列出:: sort使用define运算符来执行排序?如果是这样,为什么不排序?
干杯, 克里斯。
答案 0 :(得分:0)
我设法通过定义这个来解决这个问题:
typedef struct MyClassComparator {
bool operator()(const Node& first, const Node& second) {
//the comparison you want e.g. first fCost < second fCost etc
}
};
然后母鸡分类说:
openList.sort(MyClass Comparator());
答案 1 :(得分:0)
std :: list正在寻找
bool operator < (const Node &lhs, const Node &rhs);
,当你提供
bool operator < (Node &lhs, Node &rhs);
将签名更改为
bool operator < (const Node& rhs) const;
如果要使用类内默认运算符。或者,您的解决方案也会起作用(请注意,它具有与const相关的正确签名)。