这行代码在C++中的含义是什么?
What is the meaning of this line of code in C++?
我正在尝试学习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()
方法。
相关文章:
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 以下 C++ 代码用于 -> "#define idiv(a, b) (((a) + (b) / 2) / (b))" 是什么?
- 此代码中的操作流程是什么?C/C++.
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 此代码验证公式是什么意思?
- 这行代码到底是什么意思?
- 在nodejs中使用本机代码的最佳方法是什么?
- 无法访问的代码 在 C++11 中,可能导致这种情况的原因是什么?
- 以下与指针相关的代码的输出是什么?
- 这是什么代码?为什么它有效?C++
- 此代码中的" "是什么,它的基本作用是什么?
- 使用 gtest 框架在单元测试代码中检查目标对象的私有变量的最佳实践是什么?
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- 我的代码中针对 NQueens 问题的错误是什么?
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 这段代码"seperature | | i"是什么意思?
- 这行代码在C++中的含义是什么?
- 这是什么代码?C或C