C++ Basic Introduction to Structure/Structure Definition and Use/Structure Array/Structure Pointer/Structure Nested Structure/Structure as Function Parameter/Const Usage Scenario in Structure/Structure Case

C++ Basic Introduction to Structure/Structure Definition and Use/Structure Array/Structure Pointer/Structure Nested Structure/Structure as Function Parameter/Const Usage Scenario in Structure/Structure Case

Table of contents

1. Brief introduction

2. Structure definition and use

Three, structure array

Fourth, the structure pointer

Five, structure nested structure

Six, the structure as a function parameter

7. Const usage scenarios in structures

8. Structure case (print out the teacher data and the student data brought by the teacher)

9. Structure case (print out the result of bubble sorting the heroes in the array in ascending order by age)


1. Brief introduction

Organize some knowledge developed in C++, so that you can consult and use it in time when you encounter similar problems later.

This section introduces that structures and structures are user-defined data types, allowing users to store different data types, including structure/structure definition and use/struct array/struct pointer/structure nested structure/ Structs as function parameters/const usage scenarios/structure cases and precautions in structures. If there are deficiencies, welcome to point out, or if you have a better method, please leave a message.

2. Structure definition and use

Form: `struct structure name { structure member list};`

There are three ways to create variables through structures:

  • struct structure name variable name
  • struct structure name variable name = { member 1 value, member 2 value...}
  • Create variables by the way when defining the structure

illustrate:

  • The keyword when defining a structure is struct, which cannot be omitted
  • When creating a structure variable, the keyword struct can be omitted
  • Structure variables use the operator ''.'' to access members

code:

#include<iostream>
using namespace std;

//结构体定义
struct student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
}stu3; //结构体变量创建方式3 


int main() {

	//结构体变量创建方式1
	struct student stu1; //struct 关键字可以省略

	stu1.name = "张三";
	stu1.age = 18;
	stu1.score = 100;

	cout << "姓名:" << stu1.name << " 年龄:" << stu1.age << " 分数:" << stu1.score << endl;

	//结构体变量创建方式2
	struct student stu2 = { "李四",19,60 };

	cout << "姓名:" << stu2.name << " 年龄:" << stu2.age << " 分数:" << stu2.score << endl;


	stu3.name = "王五";
	stu3.age = 18;
	stu3.score = 80;


	cout << "姓名:" << stu3.name << " 年龄:" << stu3.age << " 分数:" << stu3.score << endl;

	system("pause");

	return 0;
}

Three, structure array

Custom structures can be put into arrays for easy maintenance

Form: `struct structure name array name[number of elements] = { {} , {} , ... {} }`

code:

#include<iostream>
using namespace std;

//结构体定义
struct student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};

int main() {

	//结构体数组
	struct student arr[3] =
	{
		{"张三",18,80 },
		{"李四",19,60 },
		{"王五",20,70 }
	};

	for (int i = 0; i < 3; i++)
	{
		cout << "姓名:" << arr[i].name << " 年龄:" << arr[i].age << " 分数:" << arr[i].score << endl;
	}

	system("pause");

	return 0;
}

Fourth, the structure pointer

Members of the structure can be accessed through pointers

illustrate:

  • The structure pointer can access the members of the structure through the -> operator

code:

#include<iostream>
using namespace std;

//结构体定义
struct student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};


int main() {

	struct student stu = { "张三",18,100, };

	struct student* p = &stu;

	p->score = 80; //指针通过 -> 操作符可以访问成员

	cout << "姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;

	system("pause");

	return 0;
}

Five, structure nested structure

A member of a struct can be another struct

illustrate:

  • In the structure, another structure can be defined as a member to solve practical problems

code:

#include<iostream>
using namespace std;

//学生结构体定义
struct student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};

//教师结构体定义
struct teacher
{
	//成员列表
	int id; //职工编号
	string name;  //教师姓名
	int age;   //教师年龄
	struct student stu; //子结构体 学生
};


int main() {

	struct teacher t1;
	t1.id = 10000;
	t1.name = "老王";
	t1.age = 40;

	t1.stu.name = "张三";
	t1.stu.age = 18;
	t1.stu.score = 100;

	cout << "教师 职工编号: " << t1.id << " 姓名: " << t1.name << " 年龄: " << t1.age << endl;

	cout << "辅导学员 姓名: " << t1.stu.name << " 年龄:" << t1.stu.age << " 考试分数: " << t1.stu.score << endl;

	system("pause");

	return 0;
}

Six, the structure as a function parameter

Pass the structure as a parameter to the function

There are two delivery methods:

  • pass by value
  • address passing

illustrate:

  • If you do not want to modify the data in the main function, pass it by value, otherwise pass it by address

code:

#include<iostream>
using namespace std;

//学生结构体定义
struct student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};

//值传递
void printStudent(student stu)
{
	stu.age = 28;
	cout << "子函数中 姓名:" << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score << endl;
}

//地址传递
void printStudent2(student* stu)
{
	stu->age = 28;
	cout << "子函数中 姓名:" << stu->name << " 年龄: " << stu->age << " 分数:" << stu->score << endl;
}

int main() {

	student stu = { "张三",18,100 };
	//值传递
	cout << "值传递:" << endl;
	printStudent(stu);
	cout << "主函数中 姓名:" << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score << endl;

	cout << endl;

	//地址传递
	cout << "地址传递:" << endl;
	printStudent2(&stu);
	cout << "主函数中 姓名:" << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score << endl;

	system("pause");

	return 0;
}

7. Const usage scenarios in structures

You can use const to prevent misuse

code:

#include<iostream>
using namespace std;

//学生结构体定义
struct student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};

//const使用场景
void printStudent(const student* stu) //加const防止函数体中的误操作
{
	//stu->age = 100; //操作失败,因为加了const修饰
	cout << "姓名:" << stu->name << " 年龄:" << stu->age << " 分数:" << stu->score << endl;

}

int main() {

	student stu = { "张三",18,100 };

	printStudent(&stu);

	system("pause");

	return 0;
}

8. Structure case (print out the teacher data and the student data brought by the teacher)

Description: The school is doing a graduation project. Each teacher leads 5 students, and there are 3 teachers in total. The requirements are as follows

  • Design the structure of students and teachers. In the structure of teachers, there are teacher names and an array storing 5 students as members
  • The members of the students have names and test scores, create an array to store 3 teachers, and assign values ​​to each teacher and the students they bring through the function
  • Finally, the teacher data and the student data brought by the teacher are printed out.

code:

#include<iostream>
using namespace std;

struct Student
{
	string name;
	int score;
};
struct Teacher
{
	string name;
	Student sArray[5];
};

void allocateSpace(Teacher tArray[], int len)
{
	string tName = "教师";
	string sName = "学生";
	string nameSeed = "ABCDE";
	for (int i = 0; i < len; i++)
	{
		tArray[i].name = tName + nameSeed[i];

		for (int j = 0; j < 5; j++)
		{
			tArray[i].sArray[j].name = sName + nameSeed[j];
			tArray[i].sArray[j].score = rand() % 61 + 40;
		}
	}
}

void printTeachers(Teacher tArray[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << tArray[i].name << endl;
		for (int j = 0; j < 5; j++)
		{
			cout << "\t姓名:" << tArray[i].sArray[j].name << " 分数:" << tArray[i].sArray[j].score << endl;
		}
	}
}

int main() {

	srand((unsigned int)time(NULL)); //随机数种子 头文件 #include <ctime>

	Teacher tArray[3]; //老师数组

	int len = sizeof(tArray) / sizeof(Teacher);

	allocateSpace(tArray, len); //创建数据

	printTeachers(tArray, len); //打印数据

	system("pause");

	return 0;
}

9. Structure case (print out the result of bubble sorting the heroes in the array in ascending order by age)

Description: Design a structure of heroes, including member names, ages, and genders; create an array of structures, and store 5 heroes in the array. Through the bubble sorting algorithm, sort the heroes in the array in ascending order according to age, and finally print the sorted results.

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"},
        {"Diaochan",19,"Female"},
code:

#include<iostream>
using namespace std;

//英雄结构体
struct hero
{
	string name;
	int age;
	string sex;
};
//冒泡排序
void bubbleSort(hero arr[], int len)
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - 1 - i; j++)
		{
			if (arr[j].age > arr[j + 1].age)
			{
				hero temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}
//打印数组
void printHeros(hero arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << "\t姓名: " << arr[i].name << " 性别: " << arr[i].sex << " 年龄: " << arr[i].age << endl;
	}
}

int main() {

	struct hero arr[5] =
	{
		{"刘备",23,"男"},
		{"关羽",22,"男"},
		{"张飞",20,"男"},
		{"赵云",21,"男"},
		{"貂蝉",19,"女"},
	};

	int len = sizeof(arr) / sizeof(hero); //获取数组元素个数

	cout << "未排序前:" << endl;
	printHeros(arr, len); //打印

	cout << "排序后:" << endl;
	bubbleSort(arr, len); //排序
	printHeros(arr, len); //打印

	system("pause");

	return 0;
}

 

Guess you like

Origin blog.csdn.net/u014361280/article/details/127606307