关于#c语言#的问题,请各位专家解答

初学者只知道怎么得到最大和最小者,但是不知道怎么给各个书排序

img

img

排序用 qsort 就可以了
定义一个函数作为参数传进去
int cmp(void *a, void *b)
{
    return strcmp(((Book *)a)->name, ((Book *)b)->name);
}

主程序

qsort(数组, 数组长度, sizeof(arr[0]), cmp);


代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

struct book
{
    string book_name;
    string book_author;
    int ticket_nums;
    int click_nums;
    int word_nums;
};

void print_book(book bk)
{
    cout << bk.book_name << " " << bk.book_author << " " << bk.ticket_nums << " "
        << bk.click_nums << " " << bk.word_nums << endl;
}

struct cmp
{
    bool operator()(const book& b1, const book& b2)
    {
        if (b1.ticket_nums == b2.ticket_nums)
            return b1.click_nums > b2.click_nums;
        else
            return b1.ticket_nums > b2.ticket_nums;
    }
};

int main()
{
    int n;
    cin >> n;
    vector<book>b;
    for (int i = 0; i < n; i++)
    {
        book tmp;
        cin >> tmp.book_name >> tmp.book_author >> tmp.ticket_nums >> tmp.click_nums >> tmp.word_nums;
        b.push_back(tmp);
    }
    sort(b.begin(), b.end(), cmp());

    for (int i = 0; i < n; i++)
    {
        print_book(b[i]);
    }
    
    system("pause");
    return 0;
}

演示结果如下:

img

供参考:

#include <stdio.h>
#include <stdlib.h>
struct book {
    char   name[60];
    char   author[20];
    int    votes;
    int    hits;
    int    words;
}b[100];
void input(struct book* pb, int n)
{
    int i;
    for (i = 0; i < n; i++)
        scanf("%s %s %d %d %d", pb[i].name, pb[i].author, 
                &pb[i].votes, &pb[i].hits, &pb[i].words);
}
void sort(struct book* pb, int n)
{
    int i, j;
    struct book tmp;
    for (i = n - 1; i > 0; i--) {
        for (j = 0; j < i; j++) {
            if (pb[j].votes < pb[j + 1].votes  ||
                pb[j].votes == pb[j + 1].votes && pb[j].hits < pb[j + 1].hits)
            {
                tmp = pb[j]; pb[j] = pb[j + 1]; pb[j + 1] = tmp;
            }
        }
    }
}
void print(struct book* pb, int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%s %s %d %d %d\n", pb[i].name, pb[i].author,
                      pb[i].votes, pb[i].hits, pb[i].words);
}

int main()
{
    int n;
    scanf("%d", &n);
    input(b, n);
    sort(b, n);
    print(b, n);
    return 0;
}