橙橙橙橙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 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器