Two processing methods for dynamic (indefinite length) structure array

To explain this problem, start with an example: PAT(A)1080 Graduate Admission

Method 1:
Define a structure array, open up a large storage space for the array, and then initialize and assign values.

#include<iostream>

using namespace std;

struct student {
    
    
	int ge;
	int gi;
	int b[6] = {
    
     0 };
};

int main()
{
    
    
	struct student *stu;
	int n, m, k;
	// n申请人总数,m研究生院总数,k申请人可以选择的数量
	cin >> n >> m >> k;
	/*
	int a[101] = { 0 }; // 每个研究生院的配额
	for (int i = 0; i < m; i++)
	{
		int g;
		cin >> g;
		a[i] = g;
	}
	*/
	//为结构体分配存储空间
	stu = (struct student *)malloc(40000* sizeof(struct student));
	for (int i = 0; i < n; i++) // 为所有学生输入他的各项信息
	{
    
    
		int c, d, e;
		cin >> c >> d;
		stu[i].ge = c;
		stu[i].gi = d;
		for (int j = 0; j < k; j++)
		{
    
    
			cin >> e;
			stu[i].b[j] = e;
		}
	}
	for (int i = 0; i < n; i++)
		for(int j=0; j<k; j++)
		cout << stu[i].ge << "  " << stu[i].gi << "  " << stu[i].b[j] << endl;

	system("pause");
	return 0;
}

Input:
3 6 3
100 100 0 1 2
60 60 2 3 5
100 90 0 3 4

Output:
Insert picture description here
Through the output, you can find that the input data is stored in the information corresponding to each student structure.

Method 2:
Use vector to perform dynamic array assignment operation

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct stu {
    
    
    int id;
    double g1, g2;
    int choice[6];
};

int main() 
{
    
    
    int n, m, k;
	cin>>n>>m>>k;
    vector<stu> students; 
	stu tmp;
    for (int i = 0; i < n; i++) 
	{
    
    
        tmp.id = i;
        int a,b;
		cin>>a>>b;
		tmp.g1=a;
		tmp.g2=b;
        for (int j = 0; j < k; j++) 
        {
    
    
            int c;
            cin>>c;
		    tmp.choice[j]=c;
		}
        students.push_back(tmp);
    }
    
	for(int i=0; i<n; i++)
	{
    
    
		for(int j=0; j<k; j++)
		cout<<students[i].g1<<"  "<<students[i].g2<<"  "<<students[i].choice[j]<<endl;
	} 
	
    return 0;
}

Input:
5 6 3
100 100 0 1 2
60 60 2 3 5
100 90 0 3 4
90 100 1 2 0
90 90 5 1 3

Output:
Insert picture description here
Through the output, you can find that the input data is stored in the information corresponding to each student structure.

Therefore, there are the above two methods for the processing of dynamic array structure. For the detailed problem solving process and code of PAT(A)1080, please refer to other blogs.

Guess you like

Origin blog.csdn.net/qq_27538633/article/details/105778167