这行代码在C++中的含义是什么?

What is the meaning of this line of code in C++?

本文关键字:是什么 代码 C++      更新时间:2023-10-16

我正在尝试学习c ++,并偶然发现了这段代码。我想知道这行特定的代码是做什么的。我对Java有一些了解,以我拙见的知识,我可以从所有其他代码行中制作一些东西。

具体代码行:bool operator > (const path& l, const path& r) {return l.cost != r.cost ? l.cost > r.cost : l.dist > r.dist;}

这是整个代码:

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct path { int cost, dist, x, y; };
bool operator > (const path& l, const path& r) {return l.cost != r.cost ? l.cost > r.cost : l.dist > r.dist;}
int r, k;
vector<vector<int>> kaart;
path solve() {                                                  // dijkstra
    vector<vector<bool>> seen(r, vector<bool>(k, false));
    priority_queue<path, vector<path>, greater<path>> queue;
    for(int i = 0; i < r; i++) queue.push(path{ 0, 0, -1, i });
    while (queue.top().x != k - 1) {
        path p = queue.top();
        queue.pop();
        if (p.x < 0 || !seen.at(p.y).at(p.x)) {
            if(p.x >= 0) seen.at(p.y).at(p.x) = true;
            queue.push(                             { p.cost + kaart.at(p.y).at(p.x + 1), p.dist + 1, p.x + 1, p.y });
            if (p.x > 0) queue.push(                { p.cost + kaart.at(p.y).at(p.x - 1), p.dist + 1, p.x - 1, p.y });
            if (p.x >= 0 && p.y > 0) queue.push(    { p.cost + kaart.at(p.y - 1).at(p.x), p.dist + 1, p.x, p.y - 1 });
            if (p.x >= 0 && p.y < r - 1) queue.push({ p.cost + kaart.at(p.y + 1).at(p.x), p.dist + 1, p.x, p.y + 1 });
        }
    }
    return queue.top();
}
int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> r >> k;
        kaart = vector<vector<int>>(r, vector<int>(k, 0));
        for (int j = 0; j < r; j++) {
            for (int l = 0; l < k; l++) {
                cin >> kaart.at(j).at(l);
            }
        }
        path sol = solve();
        cout << i << " " << sol.dist << " " << sol.cost << endl;
    }
}

C++语句

struct path { int cost, dist, x, y; };
bool operator > (const path& l, const path& r) {return l.cost != r.cost ? l.cost > r.cost : l.dist > r.dist;}

定义一个对象和一个比较运算符,用于比较其中两个对象。

直接比较两个对象的 Java 等效项是让对象实现Comparable

C++ struct类似于具有public字段的 Java 类,因此等效的 Java 代码将是:

class Path implements Comparable<Path> {
    public int cost;
    public int dist;
    public int x;
    public int y;
    @Override
    public int compareTo(Path that) {
        return this.cost != that.cost ? Integer.compare(this.cost, that.cost)
                                      : Integer.compare(this.dist, that.dist);
    }
}

通常,您会将字段更改为私有字段并添加 getter(也许还有 setter(方法。

比较运算符由priority_queue使用,Java等价的是PriorityQueue,它将使用compareTo()方法。