怎么实现Person p[n]
时间: 2023-12-11 19:05:38 浏览: 17
在C++中,可以通过定义一个Person类,然后使用数组来存储多个Person对象的方式来实现Person p[n]的功能。具体实现如下:
首先定义一个Person类:
```
class Person {
public:
string name;
int age;
};
```
然后在程序中创建一个Person类型的数组,长度为n:
```
int n = 10; // 假设需要创建10个Person对象
Person p[n]; // 定义一个Person类型的数组,长度为n
```
接着,可以对数组中的每个元素进行初始化:
```
for (int i = 0; i < n; i++) {
p[i].name = "Tom";
p[i].age = 20;
}
```
这样就可以创建一个长度为n的Person数组,并对其中的每个元素进行初始化。
相关问题
void birth sort (struct person p[],int n )实现公民信息按照生日排序的函数,排序原则,按年龄从小到大排序。其中数组p存放n个公民信息
好的,根据您提供的信息,这是一个按照生日排序的函数,按照年龄从小到大排序。以下是一种实现方式:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person {
char name[20];
int year;
int month;
int day;
};
int compare(struct person a, struct person b) {
if (a.year != b.year) {
return a.year - b.year;
}
if (a.month != b.month) {
return a.month - b.month;
}
return a.day - b.day;
}
void bubble_sort(struct person p[], int n) {
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (compare(p[j], p[j+1]) > 0) {
struct person temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}
}
void birth_sort(struct person p[], int n) {
bubble_sort(p, n);
}
int main() {
struct person people[] = {
{"Tom", 1995, 2, 3},
{"Alice", 1994, 8, 12},
{"Bob", 1997, 5, 20},
{"John", 1996, 1, 1},
};
int n = sizeof(people) / sizeof(struct person);
birth_sort(people, n);
int i;
for (i = 0; i < n; i++) {
printf("%s %d-%d-%d\n", people[i].name, people[i].year, people[i].month, people[i].day);
}
return 0;
}
```
在这个实现中,我们首先定义了一个 `struct person` 结构体,用于存储每个公民的姓名和生日信息。然后,我们实现了一个 `compare` 函数,用于比较两个 `struct person` 结构体的年龄大小。
接着,我们使用冒泡排序的算法,实现了 `bubble_sort` 函数,用于按照生日将 `struct person` 结构体数组排序。
最后,我们实现了 `birth_sort` 函数,它直接调用了 `bubble_sort` 函数来完成排序。
在 `main` 函数中,我们定义了一个 `people` 数组,存放了四个公民的信息。然后,我们调用 `birth_sort` 函数来将它们按照生日排序,最后输出排序结果。
希望这个实现能够帮助到您!
int n = check_person(name, p);
这段代码是将一个名字和一组人员进行比较,返回该名字在人员组中的位置(索引值),或者返回-1表示该名字不存在于人员组中。
具体实现方式可能会根据具体情况略有不同,但通常需要遍历整个人员组,逐一比对每个人员的名字和输入的名字是否相同。如果找到了相同的名字,则返回该人员在人员组中的位置(索引值),否则返回-1表示该名字不存在于人员组中。
需要注意的是,这里的变量name和p都需要定义并赋值,否则代码无法通过编译。