我Node对象的列表容器,其中有一个定义的比较operaion排序(见头文件)C++使用与自定义类对象的列表容器,列表::排序功能实际上并没有我的数据
节点.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
从我读,应该列出::排序使用定义操作执行排序?如果是这样,为什么不排序?
干杯, Chris。
为什么使用'new'来创建对象,这是C++而不是Java或C# –
对于初学者来说,您的示例正在泄漏所有使用new构建的Node。只需在堆栈上创建它们即可。另外,operator <是最好定义的const并接受一个const ref。但是我找不到你的排序问题......确保你的getFCost不会意外返回其中一个成本;) – heinrichj
你需要展示如何定义Node结构和getFCost(),因为它代表你的问题是不可能回答的,因为问题出现在你没有显示的代码中。此外,你应该阅读关于const正确性。 –