我正在尝试为 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++ 算法      更新时间:2023-10-16

我正在尝试为 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; });