橙橙橙橙166 2022-06-23 15:00 采纳率: 85.2%
浏览 32
已结题

c++结构体qsort


#include<iostream>
#include<iomanip>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<stdio.h>
#include<algorithm>
#include<cmath>
using namespace std;
struct stu{
    string name;
    int li;
    int shi;
}student[1010];
int cmp(const void*x,const void*y){
    struct stu* xx = (struct stu*)x;
    struct stu* yy = (struct stu*)y;
    return (yy->li+yy->shi)-(xx->li+xx->shi);
}
int main(){
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        
        for(int i=0;i<n;i++){
            cin>>student[i].name>>student[i].li>>student[i].shi;
        }
        qsort(&student[0], sizeof(student) / sizeof(student[0]), sizeof(student[0]), cmp);
        
        for(int j=0;j<n;j++){
            cout<<student[j].name<<endl;
        }
    }
    
}

为什么这会有问题?

img

  • 写回答

1条回答 默认 最新

  • 浪客 2022-06-23 15:54
    关注
    
    struct stu
    {
        char name[20]; //string name
        int li;
        int shi;
    };
    
    int cmp(const void *x, const void *y)
    {
        struct stu *xx = (struct stu *)x;
        struct stu *yy = (struct stu *)y;
        return (yy->li + yy->shi) - (xx->li + xx->shi);
    }
    int main()
    {
        int t;
        cin >> t;
        while (t--)
        {
            int n;
            cin >> n;
            struct stu *student = new struct stu[n];
    
            for (int i = 0; i < n; i++)
            {
                cin >> student[i].name >> student[i].li >> student[i].shi;
            }
            qsort(student, n, sizeof(stu), cmp);
    
            for (int j = 0; j < n; j++)
            {
                cout << student[j].name << endl;
            }
            delete student;
        }
    
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 7月1日
  • 已采纳回答 6月23日
  • 创建了问题 6月23日

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败