对结构向量进行排序

Sorting a struct vector

本文关键字:排序 向量 结构      更新时间:2023-10-16

我有一个很大的问题。.我是编程的初学者,我尝试在C 中为足球联赛排名制定一个计划,必须根据他们的分数对球队进行分类。<<<<<<<<<<<<<<<<

有人可以帮助一个想法吗?

我为具有名称和积分数的团队创建了一个结构。

我该如何对团队进行分类?对不起,我的英语不好。

这是我的代码:

#include <iostream>
#include <algorithm>
using namespace std;
//I created a struct for the team.
struct team
{
    char name;
    int pct;
}v[20];
int main()
{   int i,sw,aux;
    for(i=1;i<=4;i++)//read the names
    {   
        cout<<"Team "<<i<<endl;
        cin>>v[i].name;
    }
    for(i=1;i<=4;i++)//get the points
    {
        cout<<"Team "<<v[i].name<<" points"<<endl;
        cin>>v[i].pct;
    }
    //bubble sort(not working)
    do
    {
        sw=0;
        for(i=1;i<=4;i++)
        {
            if(v[i].pct<v[i+1].pct)
            aux=v[i].pct;
            v[i].pct=v[i+1].pct;
            v[i+1].pct=aux;
            sw=1;
        }
    }while(sw==1);
    for(i=1;i<=4;i++)
    {
        cout<<v[i].pct<<endl;
    }
    return 0;
}

您需要像这样修改排序部分。假设您正在按desc顺序进行排序。

do
{
    sw=0;
    for(i=1;i<4;i++) //< not <= ,because in case of the last element you wont have any other element after it to compare
    {
        if(v[i].pct<v[i+1].pct) // use curly brace as you want all 4 following lines to be executed when its true
        {
            aux=v[i]; //swap entire struct not just one variable
            v[i]=v[i+1];
            v[i+1]=aux;
            sw=1;
        }
    }
}while(sw==1);

还可能需要编辑团队名称的变量类型,因为它可以是字符串。

当您使用C 时,您可以使用一个衬里功能来对

进行排序
//#include<algorithm>
//define comparator function
bool cmp(team a, team b)
{
    return a.pct < b.pct;
}
sort(v+1,v+4+1,cmp);

您也可以简单地在结构内写入比较器,然后使用排序函数:

struct team
{
    char name;
    int pct;
    bool operator<(team other) const
    {
        return pct > other.pct;
    }
}v[20];
sort(v+1,v+4+1);

我很好奇您为什么包含算法,但不要使用任何算法。你知道STL吗?由于您包含算法,我想您可能知道一些简单的功能,例如交换,排序和复制。它们易于使用,您只需要键入一条线,而不是自己编写泡泡排序。在使用排序功能之前,应定义哪种顺序可以对这些团队生效。就像这样:

bool compareTeams(const Team &t1, const Team &t2) {
    if (t1.getScore() == t2.getScore()) {
        return t1.getName() < t2.getName();
    }
    else {
        return t1.getScore() < t2.getScore();
    }
}

上面的代码定义了我们考虑对团队进行分类的方向,首先,如果两个分数相等,我们首先按分数对他们进行排序,然后我们按名称对它们进行排序。最后,我们可以使用STL中现成的排序函数。现在我们定义的顺序可以使用。(我想数组V []代表团队。我对吗?(

std::sort(v, v + 20, compareTeams);