C + + learning day 8 - structure

Posted by Eric! on Tue, 07 Dec 2021 22:34:32 +0100

Structure: it is a user-defined data type and allows users to store different data types

Syntax: struct structure name {structure member list};  

There are three ways to create variables through structures:

1. struct structure name variable name

2. struct structure name variable name = {member 1 value, member 2 value};  

3. Create variables when defining structures

#include<iostream>

using namespace std;

#include<string>

//1. Create student data type: students include name, age and score
//User defined data type, a data type composed of a collection of data types
//Syntax: struct struct name {struct member list}
struct Student
{
	//Member list
	//full name
	string name;
	//Age
	int age;
	//fraction
	int score;
}s3; //2.3 create variables when defining structures

//2. Three ways to create specific students by student type
//2.1. struct structure name variable name
//2.2. struct structure name variable name = {member 1 value, member 2 value};
//2.3. Create variables when defining structures
int main1()
{
	//2.1. struct structure name variable name
	//The struct keyword can be omitted when creating variables
	struct Student s1;
	//Assign a value to the s1 attribute and access the attribute in the structure variable through
	s1.name = "Zhang San";
	s1.age = 18;
	s1.score = 100;
	cout << "full name:" << s1.name << " Age:" << s1.age << " fraction:" << s1.score << endl;

	//2.2. struct structure name variable name = {member 1 value, member 2 value};
	struct Student s2 = {"Li Si", 19, 80};
	cout << "full name:" << s2.name << " Age:" << s2.age << " fraction:" << s2.score << endl;

	//2.3. Create variables when defining structures
	s3.name = "Wang Wu";
	s3.age = 20;
	s3.score = 60;
	cout << "full name:" << s3.name << " Age:" << s3.age << " fraction:" << s3.score << endl;

	system("pause");
	return 0;
}

Structure array

Function: put the user-defined structure into the array for easy maintenance

Syntax: struct structure name array name [number of elements] = {{}, {},..., {}};  

#include<iostream>

using namespace std;

#include<string>

//Structure array
//Syntax: struct structure name array name [number of elements] = {{}, {},..., {}};  

//1. Define structure
struct Student
{
	//Member list
	//full name
	string name;
	//Age
	int age;
	//fraction
	int score;
};

int main2()
{
	//2. Create structure array
	struct Student stuArray[3] =
	{
		{"Zhang San", 18, 100},
		{"Li Si", 28, 99},
		{"Wang Wu", 38, 66}
	};

	//3. Assign values to the elements in the structure array
	stuArray[2].name = "Zhao Liu";
	stuArray[2].age = 80;
	stuArray[2].score = 60;

	//4. Traverse structure array
	for (int i = 0; i < 3; i++)
	{
		cout << "full name:" << stuArray[i].name
			<< " Age:" << stuArray[i].age
			<< " fraction:" << stuArray[i].score << endl;
	}

	system("pause");
	return 0;
}

Structure pointer

Role: access members in a structure through a pointer

Using the operator - > you can access structure properties through the structure pointer

#include<iostream>

using namespace std;

#include<string>

//Structure pointer
//Define student structure
struct Student
{
	string name;
	int age;
	int score;
};

int main3()
{
	//1. Create student structure variables
	struct Student s = { "Zhang San", 18, 100 };

	//2. Point to the structure variable through the pointer
	struct Student* p = &s;

	//3. Access the data in the structure variable through the pointer
	cout << "full name:" << p->name
		 << " Age:" << p->age
		 << " fraction:" << p->score << endl;

	system("pause");
	return 0;
}

Structure nested structure

Action: a member in a structure can be another structure

For example, each teacher tutors a student. In the structure of one teacher, record the structure of another student

#include<iostream>

using namespace std;

#include<string>

//Structure nested structure
//Define student structure
struct Student
{
	string name;
	int age;
	int score;
};

//Define teacher structure
struct Teacher
{
	int id;
	string name;
	int age;
	struct Student stu;
};

int main4()
{
	struct Teacher t;
	t.id = 10000;
	t.name = "Lao Wang";
	t.age = 50;
	t.stu.name = "Xiao Wang";
	t.stu.age = 20;
	t.stu.score = 60;

	cout << "Teacher name:" << t.name << " Teacher No.:" << t.id << " Teacher age:" << t.age
		<< " Student Name:" << t.stu.name << " Student age:" << t.stu.age << " Student scores:" << t.stu.score << endl;

	system("pause");
	return 0;
}

Structure as function parameter

Function: pass structure as parameter to function

Two transfer methods: value transfer and address transfer

#include<iostream>

using namespace std;

#include<string>

//Structure as function parameter
//Pass the student into a parameter and print all the information on the student

//Define student structure
struct Student
{
	string name;
	int age;
	int score;
};

//Print student information
//pass by value
void printStudent1(struct Student s)
{
	s.age = 100;
	cout << "Print name in subfunction:" << s.name << " Age:" << s.age << " fraction:" << s.score << endl;
}
//Address delivery
void printStudent2(struct Student* p)
{
	p->age = 200;
	cout << "Print name in subfunction:" << p->name << " Age:" << p->age << " fraction:" << p->score << endl;
}

int main5()
{
	//Create student structure variable
	struct Student s = { "Zhang San", 20, 85 };

	//printStudent1(s);
	printStudent2(&s);
	
	cout << "main Print name in function:" << s.name << " Age:" << s.age << " fraction:" << s.score << endl;

	system("pause");
	return 0;
}

const usage scenario in structure

Function: use const to prevent misoperation

#include<iostream>

using namespace std;

#include<string>

//const usage scenario in structure

//Define student structure
struct Student
{
	string name;
	int age;
	int score;
};

//Changing the formal parameter in the function to a pointer can reduce the memory space and will not copy a new copy
void printStudent(const struct Student* s)
{
	//s->age = 150; // After const is added, an error will be reported once there is a modified operation, which can prevent our misoperation
	cout << "full name:" << s->name << " Age:" << s->age << " fraction:" << s->score << endl;
}

int main6()
{
	//Create student structure variable
	struct Student s = { "Zhang San", 15, 70 };

	//Print structure variable information through function
	printStudent(&s);
	cout << "main Print name in function:" << s.name << " Age:" << s.age << " fraction:" << s.score << endl;


	system("pause");
	return 0;
}

Structural case 1

Case description: the school is working on the completion project. Each teacher leads 5 students, with a total of 3 teachers. The needs are as follows:

Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members

Students' members have names and test scores. Create an array to store 3 teachers, and assign values to each teacher and students through functions

Finally, print out the teacher data and the student data brought by the teacher.

#include<iostream>

using namespace std;

#include<string>

#include<ctime>

//Structural case 1
/*
The school is working on the completion project. Each teacher leads 5 students, with a total of 3 teachers. The needs are as follows:

Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members

Students' members have names and test scores. Create an array to store 3 teachers, and assign values to each teacher and students through functions

Finally, print out the teacher data and the student data brought by the teacher.
*/

//Define student structure
struct Student1
{
	string sName; //full name
	int score; //fraction
};

//Define teacher structure
struct Teacher1
{
	string tName; //full name
	struct Student1 sArray[5]; //Student array
};

//A function that assigns values to teachers and students
void allocateSpace(struct Teacher1 tArray[], int len)
{
	string nameSeed = "ABCDE";
	//Start assigning values to the teacher
	for (int i = 0; i < len; i++)
	{
		tArray[i].tName = "Teacher_";
		tArray[i].tName += nameSeed[i];

		//Assign values to the students brought by each teacher through a loop
		for (int j = 0; j < 5; j++)
		{
			tArray[i].sArray[j].sName = "Student_";
			tArray[i].sArray[j].sName += nameSeed[j];

			int random = rand() % 61 + 40; //40~100
			tArray[i].sArray[j].score = random;
		}
	}
}

//Print all information
void printInfo(struct Teacher1 tArray[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << "Teacher name:" << tArray[i].tName << endl;
		for (int j = 0; j < 5; j++)
		{
			cout << "\t Student Name:" << tArray[i].sArray[j].sName
				<< " Test score:" << tArray[i].sArray[j].score << endl;
		}
	}
}

int main7()
{
	//Random number seed
	srand((unsigned int)time(NULL));

	//1. Create an array of 3 teachers
	struct Teacher1 tArray[3];

	//2. Assign values to the information of 3 teachers and the information of students brought by the teacher through the function
	int len = sizeof(tArray) / sizeof(tArray[0]);
	allocateSpace(tArray, len);

	//3. Print the information of all teachers and students
	printInfo(tArray, len);

	system("pause");
	return 0;
}

Structural case 2

Case description: design a hero structure, including member name, age and gender, create a structure array, and store 5 heroes in the array. Through the bubble sorting algorithm, the heroes in the array are sorted in ascending order according to their age, and the sorted results are finally printed.

The information of the five heroes is as follows:
         {"Liu Bei", 23, "male"},
         {"Guan Yu", 22, "male"},
         {"Zhang Fei", 20, "male"},
         {"Zhao Yun", 21, "male"},
         {"Diao Chan", 19, "female"},

#include<iostream>

using namespace std;

#include<string>

//Structural case 2
/*
Design a hero structure, including member name, age and gender, create a structure array, and store 5 heroes in the array.

Through the bubble sorting algorithm, the heroes in the array are sorted in ascending order according to their age, and the sorted results are finally printed.
*/

//1. Design hero structure
struct Hero
{
	//full name
	string name;
	//Age
	int age;
	//Gender
	string sex;
};

//Bubble sorting
void bubbleSort(struct Hero heroArray[], int len)
{
	for (int i = 0; i < len-1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
			if (heroArray[j].age > heroArray[j + 1].age)
			{
				struct Hero temp = heroArray[j];
				heroArray[j] = heroArray[j + 1];
				heroArray[j + 1] = temp;
			}
		}
	}
}

//Print array
void printHero(struct Hero heroArray[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << "full name:" << heroArray[i].name << " Age:" << heroArray[i].age << " Gender:" << heroArray[i].sex << endl;
	}
}

int main8()
{
	//2. Create an array of 5 heroes
	struct Hero heroArray[5] =
	{
		{"Liu Bei", 23, "male"},
		{"Guan Yu", 22, "male"},
		{"Fei Zhang", 20, "male"},
		{"Zhao Yun", 21, "male"},
		{"army officer's hat ornaments", 19, "female"},
	};

	int len = sizeof(heroArray) / sizeof(heroArray[0]);

	/*for (int i = 0; i < len; i++)
	{
		cout << "Name: "< heroarray [i]. Name < < age:" < heroarray [i]. Age < < gender: "< heroarray [i]. Sex < < endl;
	}*/

	//3. Sort the array in ascending order by age
	bubbleSort(heroArray, len);

	//4. Print and output the sorted results
	printHero(heroArray, len);

	system("pause");
	return 0;
}

Topics: C++ Back-end