A1047 Student List for Course (25) vector解法

本文探讨了在处理大量数据时使用C++的技巧,特别是在字符串操作和排序方面。通过实例代码展示了如何读取和组织数据,以及如何利用比较函数进行有效排序。

数据量大的时候用string会使最后一个测试点超时。

#include<cstdio>
#include<iostream>
#include<vector>
#include <algorithm>
#include<cstring>
using namespace std; 
const int maxn=40010;
const int maxc=2510;
vector<string>a[2500];
char name[maxn][5];
vector<int>course[maxc];
bool cmp1(int a,int b)
{
	return strcmp(name[a],name[b])<0;
}
int main()
{
   int n,k;
   cin>>n>>k;
   for (int i=0;i<n;i++)
   {
   	   int num;
	   scanf("%s %d",name[i],&num);
	   for (int j=0;j<num;j++)
	   {
	   	int temp;
	   	scanf("%d",&temp);
	   	course[temp].push_back(i);
	   }
   }
   for (int i=1;i<=k;i++)
   {
   	printf("%d %d\n",i,course[i].size());
   	sort(course[i].begin(),course[i].end(),cmp1);
   	for (int j=0;j<course[i].size();j++)
   	{
   		printf("%s\n",name[course[i][j]]);
	}
   }
}
在C++中,使用 `std::vector<Student>` 声明一个包含 `Student` 对象的容器需要确保类或结构体 `Student` 已经定义,并且需要包含 `<vector>` 头文件。以下是一个完整的声明和使用的示例: ### 声明与初始化 首先定义 `Student` 结构体,然后声明 `std::vector<Student>` 容器并进行操作: ```cpp #include <iostream> #include <vector> #include <string> // 定义 Student 结构体 struct Student { std::string name; int age; // 构造函数(可选) Student(const std::string& n, int a) : name(n), age(a) {} }; int main() { // 声明 vector<Student> 容器 std::vector<Student> students; // 添加元素到 vectorstudents.push_back(Student("Alice", 20)); students.push_back(Student("Bob", 22)); students.push_back(Student("Charlie", 21)); // 访问 vector 中的元素 for (const auto& student : students) { std::cout << "Name: " << student.name << ", Age: " << student.age << std::endl; } return 0; } ``` ### 解释代码 - **结构体定义**:`Student` 包含两个成员变量 `name` 和 `age`。 - **构造函数**:提供了一个用于方便初始化的构造函数。 - **声明 vector**:`std::vector<Student> students;` 表示一个存储 `Student` 对象的动态数组。 - **添加元素**:通过 `push_back()` 方法向容器中添加对象。 - **遍历容器**:使用范围 `for` 循环访问每个元素。 ### 使用注意事项 - 如果 `Student` 是一个类而不是结构体,则需要确保其具有适当的构造函数以及访问权限。 - 可以通过下标运算符 `[]` 或迭代器来访问 `vector` 中的元素。 - 需要包含头文件 `<vector>` 才能使用 `std::vector`。 ### 示例输出 ``` Name: Alice, Age: 20 Name: Bob, Age: 22 Name: Charlie, Age: 21 ``` ### 相关问题
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值