c++ struct map list 排序的小程序

本文展示了一个使用C++进行学生分数管理的例子,通过map和list容器实现学生的姓名与分数的映射,并演示了如何利用自定义比较函数对分数进行降序排序,以及对排序后的结果进行反转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include <iostream>
#include <string>
#include <map>
#include <list>

using namespace std;
struct student_score {
    char name[16];
    int score;
};

int cmp(student_score a, student_score b)
{
    return a.score > b.score;
}

int main()
{
    map<string , int> ScoreMap = {
        {"卢珍", 82}, {"童云", 88}, {"童贞", 71},
        {"蒋成", 68}, {"姚伟", 98}, {"谢建国", 78}
    }; // C++ 11X 容器方便初始化 和 auto遍历

    list<student_score> ScoreList;
    student_score tmp;
    cout << string(30, '_') << " 建立MAP时的排序 " << string(30, '_') << endl;
    for (auto it = ScoreMap.begin(); it != ScoreMap.end() ; ++it) {
        cout << it->first << "\t=> " << it->second  << endl;
        strcpy(tmp.name, it->first.c_str());
        tmp.score = it->second;
        ScoreList.push_back(tmp);
    }
    cout << string(30, '_') << " 按成绩降序排序 " << string(30, '_') << endl;
    ScoreList.sort(cmp);
    for (auto it = ScoreList.begin(); it != ScoreList.end() ; ++it) {
        cout << it->name << "\t=> " << it->score  << endl;
    }
    cout << string(30, '_') << "   反转排序  " << string(30, '_') << endl;
    ScoreList.reverse();
    for (auto it = ScoreList.begin(); it != ScoreList.end() ; ++it) {
        cout << it->name << "\t=> " << it->score  << endl;
    }
    return 0;
}

引用 http://blog.youkuaiyun.com/hongwenjun/article/details/7359720
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值