这行代码在C ++中是什么意思? [处于保留状态]

问题描述 投票:-4回答:1

我正在尝试学习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;
    }
}

java c++
1个回答
5
投票

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 ++ Comparable就像是带有struct字段的Java类,因此等效的Java代码为:

public

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

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); } } 使用比较运算符,而Java等效项是priority_queue,它将使用PriorityQueue方法。

© www.soinside.com 2019 - 2024. All rights reserved.