vector练习题

题目链接
题目描述
翻译:
对应翻译

输入:

11 5
4 7
BOB5 DON2 FRA8 JAY9 KAT3 LOR6 ZOE1
1 4
ANN0 BOB5 JAY9 LOR6
2 7
ANN0 BOB5 FRA8 JAY9 JOE4 KAT3 LOR6
3 1
BOB5
5 9
AMY7 ANN0 BOB5 DON2 FRA8 JAY9 KAT3 LOR6 ZOE1
ZOE1 ANN0 BOB5 JOE4 JAY9 FRA8 DON2 AMY7 KAT3 LOR6 NON9

输出:

ZOE1 2 4 5
ANN0 3 1 2 5
BOB5 5 1 2 3 4 5
JOE4 1 2
JAY9 4 1 2 4 5
FRA8 3 2 4 5
DON2 2 4 5
AMY7 1 5
KAT3 3 2 4 5
LOR6 4 1 2 4 5
NON9 0

代码:

#include<bits/stdc++.h>

using namespace std;

vector <int> a[26*26*26*10+1];//用来记录名字,3个大写字母+1个数字

int getid(char str[])//把名字转换成数字记录
{
    int id=0,i;
    for(i=0; i<3; i++)
        id=id*26+str[i]-'A';
    id=id*10+str[3]-'0';
    return id;
}

int main()
{
    int n,m,i,num,sum,id;
    char str[50];
    scanf("%d%d",&n,&m);//n个学生
    while(m--)//m个课程
    {
        scanf("%d%d",&num,&sum);//课程号是num,选课人数是sum
        while(sum--)
        {
            scanf("%s",str);//选课学生的名字
            id=getid(str);//转换成数字
            a[id].push_back(num);//存进vector里面
        }
    }
    while(n--)//遍历n个学生
    {
        scanf("%s",str);//读入学生的名字
        id=getid(str);
        printf("%s",str);
        sort(a[id].begin(),a[id].end());//把该学生选的课程按课程号从小到大排序
        printf(" %d",a[id].size());//输出该学生一共选了多少课程
        for(i=0; i<a[id].size(); i++)//分别输出课程对应的课程号
            printf(" %d",a[id][i]);
        printf("\n");
    }
    return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中,结构体排序练习通常涉及到如何使用标准库中的算法对包含自定义数据类型的结构体数组或容器进行排序。这里我们可以举一个简单的例子,假设有一个名为`Student`的结构体,包含`name`和`age`两个成员: ```cpp struct Student { std::string name; int age; }; ``` 你可以用以下几种方法对`Student`结构体数组进行排序: 1. **直接排序:**如果年龄是排序的主要依据,你可以定义一个比较函数(`compare`),然后使用`std::sort`函数: ```cpp bool compareStudents(const Student& s1, const Student& s2) { return s1.age < s2.age; } int main() { Student students[] = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::sort(students, students + sizeof(students) / sizeof(students), compareStudents); // 现在students数组按年龄升序排列 } ``` 2. **使用STL算法:**如果你的结构体已经实现了`<`运算符,那么可以直接使用`std::stable_sort`: ```cpp bool studentLess(const Student& s1, const Student& s2) { return s1.age < s2.age; } int main() { std::vector<Student> students = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::stable_sort(students.begin(), students.end(), studentLess); } ``` 3. **自定义比较器(C++11及以上):**也可以使用lambda表达式来创建一个可传递的比较器: ```cpp int main() { std::vector<Student> students = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::sort(students.begin(), students.end(), [](const Student& s1, const Student& s2) { return s1.age < s2.age; }); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值