Wiki
Structures and Unions
Existing English translations were reused. 3 current source blocks remain in Simplified Chinese, without triggering paid translation.
1.Structure
1.1.Basic Concepts of Structures
A struct is a user-==defined data type== that allows users to store different data types.
1.2.Struct definition and usage
Syntax:struct 结构体名 { 结构体成员列表 };
There are three ways to create a variable from a struct:
- struct structName variableName
- struct structName variableName = { member1Value, member2Value...}
- Create variables while defining the struct
Example:
//结构体定义
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;
return 0;
}
Operation result:
姓名:张三 年龄:18 分数:100
姓名:李四 年龄:19 分数:60
姓名:王五 年龄:18 分数:80
Summary 1: When defining a structure, the keyword is struct and cannot be omitted.
Summary 2: When creating a structure variable, the keyword struct can be omitted
Summary 3: Struct variables use the operator '.' to access members.
1.3.Array of structs
**Purpose:** Place custom structures into an array for easy maintenance.
Syntax: struct 结构体名 数组名[元素个数] = { {} , {} , ... {} }
Example:
//结构体定义
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;
}
return 0;
}
Run result: Compilation failed: the struct definition is missing a semicolon at the end ;, and the program will not generate an executable file.
1.4.structure pointer
**Purpose:** To access members within a structure through a pointer
- Use the operator
->to access structure members through a structure pointer
Example:
//结构体定义
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;
return 0;
}
Operation result:
姓名:张三 年龄:18 分数:80
Summary: A struct pointer can access members within the struct through the -> operator.
1.5.Nested structure within a structure
Function: A member in a structure can be another structure
**For example:** Each teacher tutors one student; in a teacher's struct, a student's struct is recorded.
Example:
//学生结构体定义
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;
return 0;
}
Operation result:
教师 职工编号: 10000 姓名: 老王 年龄: 40
辅导学员 姓名: 张三 年龄:18 考试分数: 100
**Summary:** A structure can contain another structure as a member to solve practical problems.
1.6.Structure as a function parameter
**Purpose:** Pass a structure as a parameter to a function
There are two transmission methods:
- Pass by value
- Pass by address
Example:
//学生结构体定义
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};
//值传递
printStudent(stu);
cout << "主函数中 姓名:" << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score << endl;
cout << endl;
//地址传递
printStudent2(&stu);
cout << "主函数中 姓名:" << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score << endl;
return 0;
}
Operation result:
子函数中 姓名:张三 年龄: 28 分数:100
主函数中 姓名:张三 年龄: 18 分数:100
子函数中 姓名:张三 年龄: 28 分数:100
主函数中 姓名:张三 年龄: 28 分数:100
Summary: If you do not want to modify the data in the main function, use pass-by-value; otherwise, use pass-by-address.
1.7.Usage scenarios of const in structs
**Purpose:** Use const to prevent accidental modification
Example:
//学生结构体定义
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);
return 0;
}
Operation result:
姓名:张三 年龄:18 分数:100
1.8.Structure case
1.8.1.Case 1
案例描述:
The school is working on a graduation project, with each teacher leading 5 students, and there are a total of 3 teachers. The requirements are as follows:
Design structures for students and teachers, where the teacher structure has the teacher's name and an array holding 5 students as members.
The student members include name and exam score. Create an array to store 3 teachers, and assign values to each teacher and the students they supervise through a function.
Finally, print out the teacher data as well as the student data associated with the teacher.
Example:
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); //打印数据
return 0;
}
Run results (random numbers vary with the runtime environment; the following is an example from one run; type sizes or type names may vary with the compiler and platform):
教师A
姓名:学生A 分数:81
姓名:学生B 分数:43
姓名:学生C 分数:88
姓名:学生D 分数:95
姓名:学生E 分数:81
教师B
姓名:学生A 分数:78
姓名:学生B 分数:73
姓名:学生C 分数:85
姓名:学生D 分数:99
姓名:学生E 分数:54
教师C
姓名:学生A 分数:42
姓名:学生B 分数:79
姓名:学生C 分数:74
姓名:学生D 分数:100
姓名:学生E 分数:89
1.8.2.Case 2
案例描述:
Design a struct for a hero, including member name, age, and gender; create an array of structs, storing 5 heroes in the array.
Using the bubble sort algorithm, sort the heroes in the array in ascending order by age, and finally print the sorted result.
The information of the five heroes is as follows:
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"},
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
Example:
//英雄结构体
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 << "姓名: " << 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); //获取数组元素个数
bubbleSort(arr, len); //排序
printHeros(arr, len); //打印
return 0;
}
Run result (type size or type name may vary depending on compiler and platform):
姓名: 貂蝉 性别: 女 年龄: 19
姓名: 张飞 性别: 男 年龄: 20
姓名: 赵云 性别: 男 年龄: 21
姓名: 关羽 性别: 男 年龄: 22
姓名: 刘备 性别: 男 年龄: 23
2.
2.1.Differences in struct syntax between C and C++
2.1.1.Define a structure
A structure definition consists of the keyword struct and the structure name; the structure name can be defined as needed.
The struct statement defines a new data type containing multiple members. The format of the struct statement is as follows:
struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
2.1.2.Access structure members
下面是声明一个结构体类型 Books ,变量为 book, 为了访问结构的成员,我们使用 成员访问运算符(.) 。成员访问运算符是结构变量名称和我们要访问的结构成员之间的一个句号。
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
book.book_id = 1;
strcpy(book.title,"春天");
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
typedef struct Books //Books可忽略不写
{
char title[50];
char author[50];
char subject[100];
int book_id;
}Books_Rename;
struct Books book; //第一种写法,不使用typedf必须加 struct 定义结构体
Books_Rename book; //用typedef后的写法,9,11行不能共存,因为变量名相同。
book.book_id = 1;0
strcpy(book.title,"春天");
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
2.1.3.Pointer to a structure
You can define pointers to structures in the same way as you define pointers to other types of variables, as shown below:
struct Books *struct_pointer;
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
Now, you can store the address of a structure variable in the pointer variable defined above. To find the address of a structure variable, place the & operator before the name of the structure, as shown below:
struct_pointer = &Book1;
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
To access a member of a structure using a pointer to that structure, you must use the -> operator, as shown below:
struct_pointer->title;
(*struct_pointer).title;
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
2.1.4.Structures and Functions
- as a function argument
struct Books
{
···
int book_id;
} book;
void fun1(Books book){
}
//通常使用指针传递
void fun2(Books *book){
}
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
- as a function return type
2.1.5.Struct in C++
- Definition Consistent with the above definition, except that in C++ , even if typedef struct is not used to define a structure, when defining a structure variable, there is no need to add struct before the variable.
//定义结构体
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
//定义结构体变量
book book1;
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
- Object-oriented
structThe default members and inheritance arepublic
struct Books
{
public://默认
string title;
string author;
string subject;
int book_id;
//构造函数
Books(string t,string author,string subject,int id){
title = t;
author = author;
subject = subject;
book_id = id;
}
//析构函数
~Books(){
...
}
//成员函数
void fun1(){
...
}
private:
protected:
};
//初始化结构体
Books book1("title","author","subject",1);
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
2.2.union
A union is a special data type that allows you to store different data types in the same memory location. You can define a union with multiple members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location.
2.2.1.Define union
To define a union, you must use the union statement in the same way as defining a structure. The union statement defines a new data type with multiple members. The format of the union statement is as follows:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
//举例:
union Type_Name
{
int i;
float f;
char str1[20];
string str2;
} object_name;
//调用方式
object_name.i = 5;
object_name.f = 6.0f;
object_name.str2 = "你好!";
Run result: This code block does not contain the main function; it is a syntax, interface, or multi-file example and cannot be run independently, so there is no terminal output.
Note: The memory size occupied by a union is determined by the largest memory requirement among its member variables.