我正在尝试为 Kruskal 算法实现一个C++程序,该程序需要我按权重对图形进行排序。如何按权重对结构进行排序
I'm trying to implement a C++ program for Kruskal algorithm which requires me to sort the graph by weights.How can I sort my STRUCTURE by WEIGHTS
我正在尝试为 Kruskal 算法实现一个C++程序,该程序需要我按权重对图形进行排序。我正在尝试使用向量(结构),但排序函数似乎给出了所有零。如何按权重对结构进行排序。
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct graph
{
int src;
int dst;
int weight;
};
bool compare(struct graph a,struct graph b)
{
return (&a.weight < &b.weight);
}
int main()
{
int ver,edges;
cin >> ver >> edges;
vector<graph> G(100);
for(int i=0; i<edges; ++i)
{
cin >> G[i].src >> G[i].dst >> G[i].weight;
}
sort(G.begin(),G.end(),compare); //trying to sort by weights
for(int i=0; i<edges; ++i)
{
cout << G[i].src << G[i].dst << G[i].weight << endl;
}
}
中的&
bool compare(struct graph a,struct graph b)
{
return (&a.weight < &b.weight);
}
获取地址,即您不是在比较权重,而是在比较它们的地址。只需省略&
,但也避免不必要的复制,并通过常量引用获取图参数,即
bool compare(graph const & a, graph const & b)
{
return a.weight < b.weight;
}
最后,您可以直接通过 lambda 执行此操作,如
std::sort(G.begin(), G.end(),[](graph const&l, graph const&r)
{ return l.weight < r.weight; });
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 我正在尝试为 Kruskal 算法实现一个C++程序,该程序需要我按权重对图形进行排序。如何按权重对结构进行排序