简单的二级结构体排序

**题目信息**

  1. 利用 sort 函数
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

struct good
{

    char name[35];
    double price;
};

typedef struct good gg;

int cmp(gg a, gg b)
{

    if(a.price != b.price)
	{
        return a.price < b.price;
    }

	return strcmp(a.name, b.name) < 0;
}



void mysort(gg a[], int n)
{

    gg tmp;

	int i, j, idx=0;

    for(i=0; i<n-1; i++)
	{
        for(j=i+1; j<n; j++)
		{
            if(cmp(a[i], a[j]) == 0)
			{
                idx = j;
            }
        }
        tmp = a[i];

		a[i] = a[idx];

		a[idx] = tmp;
    }
}


int main()
{

    int i, n, m, p, z, y, g, h;

	scanf("%d%d", &n, &m);

    double t;
    gg a[110];

    for(i=0; i<n; i++)
	{

        scanf("%s", a[i].name);
        scanf("%d%d%d%d%d", &p, &z, &y, &g, &h);

        t = z == 0 ? p : p*(0.1*z);
        t = g == 0 ? t : (t >= g ? t-h : t);
        t += y;

        a[i].price = t;
    }

    mysort(a, n);

    sort(a, a+n, cmp);

    for(i=0; i<m; i++)
	{
        printf("%s %.2f\n", a[i].name, a[i].price);
    }

    return 0;
}
  1. 利用 qsort 函数(参考 ① && ② )
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

struct good
{

    char name[35];
    double price;
};

typedef struct good gg;

// qsort
int cmp(const void *x, const void *y)
{

    gg *a = (gg *)x;
    gg *b = (gg *)y;

    if(a->price != b->price)
	{
        return a->price > b->price;
    }
    return strcmp(a->name, b->name) > 0;
}


int main()
{

    int i, n, m, p, z, y, g, h;
    scanf("%d%d", &n, &m);

    double t;
    gg a[110];

    for(i=0; i<n; i++)
	{

        scanf("%s", a[i].name);
        scanf("%d%d%d%d%d", &p, &z, &y, &g, &h);

        t = z==0 ? p : p*(0.1*z);
        t = g==0 ? t : (t>=g ? t-h : t);
        t += y;

        a[i].price = t;
    }

    qsort(a, n, sizeof(gg), cmp);

    for(i=0; i<m; i++)
	{
        printf("%s %.2f\n", a[i].name, a[i].price);
    }

    return 0;
}

你可能感兴趣的:(筑基)