C 使用与自定义类对象的列表容器,列表:: Sort函数实际上并未对我的数据进行排序

c++ Using the list container with custom class Objects, the list::sort function does not actually sort my data

本文关键字:列表 函数 实际上 排序 数据 我的 Sort 自定义 对象      更新时间:2023-10-16

我有一个节点对象的列表容器,该列表具有定义的比较歌剧(请参阅标题文件)

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

从我阅读的内容中,应该列表::排序使用定义操作员执行排序?如果是这样,为什么不排序?

欢呼,克里斯。

我设法通过此处解决了这一点:

typedef struct MyClassComparator {
    bool operator()(const Node& first, const Node& second) {
        //the comparison you want e.g. first fCost < second fCost etc
    }
};

然后母鸡分类说:

openlist.sort(myClassComparator());

std :: list正在寻找

bool operator < (const Node &lhs, const Node &rhs);

当您提供

bool operator < (Node &lhs, Node &rhs);

将签名更改为

bool operator < (const Node& rhs) const;

如果要使用课堂默认操作员。或者,您的解决方案也可以工作(请注意,它具有与const的适当签名)。