Skip to content

第 12 章:结构体——把数据组织起来 ​

本章能学到什么 ​

  • 为什么需要把「一包」相关数据捆在一起
  • C++ struct 的定义、使用和结构体数组
  • 结合上一章的 sort,给一组学生排名次
  • 和 Python 字典的对照

知识链位置:第 10 章的容器装的是「同一种东西排成队」,比如一串分数。本章再进一步:把不同种类的数据——姓名、学号、三科成绩——捆成一包。

场景:一个学生不止一个数字 ​

第 11 章的成绩单用了两个数组:一个装姓名,一个装分数。这能工作,但很脆弱——两个数组靠「下标相同」来对应,一旦一个数组动了,对应关系就乱了。

真实的学生信息更复杂:姓名、学号、语文、数学、英语,一共 5 项。用平行数组就要 5 个数组,对应关系全靠自己小心维护。

更好的办法是把这 5 项捆成一包:一个学生 = 一个数据包。100 个学生 = 100 个数据包排成队。这个「包」在 C++ 里叫结构体(struct)。

定义一个结构体 ​

cpp
struct Student {
    string name;     // 姓名
    int id;          // 学号
    int chinese;     // 语文成绩
    int math;        // 数学成绩
    int english;     // 英语成绩
};

这段代码不制造任何数据,它只是设计图纸:告诉编译器「Student 这种包里有哪几格、每格装什么类型」。图纸定好了,才能照着造出一个个具体的学生。

术语含义类比
结构体(struct)数据包的设计图纸月饼模具
成员包里的一格数据模具上的一个花纹
结构体变量照图纸造出的一个具体的包压出来的一块月饼

使用结构体变量 ​

造出一个学生,用 .(点号)访问包里的每一格:

cpp
#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int id;
    int chinese;
    int math;
    int english;
};

int main() {
    Student ming;                 // 照图纸造出一个学生
    ming.name = "小明";           // 用点号往格里装数据
    ming.id = 1;
    ming.chinese = 88;
    ming.math = 92;
    ming.english = 79;

    int total = ming.chinese + ming.math + ming.english;
    cout << ming.name << "(学号" << ming.id << ")总分:" << total << endl;
    return 0;
}
text
小明(学号1)总分:259

ming.chinese 读作「ming 这个包的 chinese 那一格」。它就是一个普通的 int,能参加任何计算。

也可以在造出来的同时就装好数据:

cpp
Student hong = {"小红", 2, 95, 81, 90};   // 按图纸里的顺序给值

结构体数组:一个班的学生 ​

图纸 + 数组 = 全班。每个数组元素都是一个完整的数据包:

cpp
#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int id;
    int chinese;
    int math;
    int english;
};

int main() {
    Student cls[3] = {                        // 结构体数组
        {"小明", 1, 88, 92, 79},
        {"小红", 2, 95, 81, 90},
        {"小刚", 3, 70, 85, 88}
    };

    for (int i = 0; i < 3; i++) {
        int total = cls[i].chinese + cls[i].math + cls[i].english;
        cout << cls[i].name << " 总分:" << total << endl;
    }
    return 0;
}
text
小明 总分:259
小红 总分:266
小刚 总分:243

对比第 11 章的平行数组写法,好处很实在:

对比点平行数组结构体数组
一个学生的数据分散在 5 个数组里装在一个包里
交换两个学生5 个数组都要交换交换两个包即可
传给学生处理函数传 5 个参数传 1 个包
新增一项(如体育分)再加一个数组图纸里加一格

结构体里还能装结构体 ​

数据包里的某一格,本身也可以是另一个包。比如「一个学生有住址,住址有城市和街道」:

cpp
#include <iostream>
#include <string>
using namespace std;

struct Address {
    string city;
    string street;
};

struct Student {
    string name;
    int id;
    Address addr;               // 有一格是另一个结构体
};

int main() {
    Student ming = {"小明", 1, {"芒市", "团结大街"}};
    cout << ming.name << "住在" << ming.addr.city << ming.addr.street << endl;
    return 0;
}
text
小明住在芒市团结大街

ming.addr.city 连续用两个点号:先取出 ming 的 addr 格,再取 addr 的 city 格。一层一层往下找。

三个容易踩的坑 ​

坑现象对策
定义末尾忘写分号struct Student { ... } 后面少 ;,报错行号指向很奇怪的地方结构体定义以 }; 结尾
初始化顺序不对{"小明", 88, 1} 把分数装进了学号格大括号里的值按图纸里的顺序装格
成员名写错ming.chinees 编译报错「没有这个成员」编译器当场拦住,按提示改正即可

配合 sort:按总分排名次 ​

结构体和上一章的 sort 能直接配合。只需告诉 sort「两个包谁排前面」——写一个比较规则:

cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

struct Student {
    string name;
    int id;
    int chinese;
    int math;
    int english;
};

// 比较规则:a 的总分比 b 高,a 就排前面
bool higherFirst(const Student& a, const Student& b) {
    int ta = a.chinese + a.math + a.english;
    int tb = b.chinese + b.math + b.english;
    return ta > tb;
}

int main() {
    Student cls[3] = {
        {"小明", 1, 88, 92, 79},
        {"小红", 2, 95, 81, 90},
        {"小刚", 3, 70, 85, 88}
    };

    sort(cls, cls + 3, higherFirst);   // 第三个参数是比较规则

    for (int i = 0; i < 3; i++) {
        int total = cls[i].chinese + cls[i].math + cls[i].english;
        cout << "第" << i + 1 << "名:" << cls[i].name
             << "(" << total << "分)" << endl;
    }
    return 0;
}
text
第1名:小红(266分)
第2名:小明(259分)
第3名:小刚(243分)

higherFirst 返回 true 表示「a 应该站在 b 前面」。sort 拿着这把尺子反复比较,就排出了名次。

结构体配 vector:人数不固定的班级 ​

结构体数组的大小写死了 3 人,转来新同学怎么办?第 10 章的 vector 可以直接装结构体:

cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Student {
    string name;
    int chinese;
    int math;
};

int main() {
    vector<Student> cls;
    cls.push_back({"小明", 88, 92});   // 随时加人
    cls.push_back({"小红", 95, 81});
    cls.push_back({"小刚", 70, 85});   // 插班生来了,再 push 一个

    for (int i = 0; i < (int)cls.size(); i++) {
        cout << cls[i].name << " 总分:" << cls[i].chinese + cls[i].math << endl;
    }
    return 0;
}
text
小明 总分:180
小红 总分:176
小刚 总分:155

vector<Student> 读作「装 Student 的 vector」。容器管排队,结构体管打包,各管一段,配合使用。

返回结构体的函数 ​

函数不只接收结构体,也能造一个返回:

cpp
#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int chinese;
    int math;
};

Student makeStudent(string n, int c, int m) {   // 返回值类型是 Student
    Student s;
    s.name = n;
    s.chinese = c;
    s.math = m;
    return s;                                   // 整个包返回
}

int main() {
    Student ming = makeStudent("小明", 88, 92);
    cout << ming.name << " 总分:" << ming.chinese + ming.math << endl;
    return 0;
}
text
小明 总分:180

makeStudent 像一个「注册窗口」:交进去零散的信息,领出来一个装好的包。这种「造对象的函数」,正是下一章构造函数的预告。

完整例子:成绩登记系统 ​

把本章内容合起来:结构体装一个学生,vector 装全班,函数管打印,sort 管排名。

cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student {
    string name;
    int chinese;
    int math;
    int english;
};

int totalScore(const Student& s) {          // 算一个学生的总分
    return s.chinese + s.math + s.english;
}

bool higherFirst(const Student& a, const Student& b) {  // sort 用的比较规则
    return totalScore(a) > totalScore(b);
}

void printReport(const vector<Student>& cls) {          // 打印全班名次表
    for (int i = 0; i < (int)cls.size(); i++) {
        cout << "第" << i + 1 << "名:" << cls[i].name
             << "(" << totalScore(cls[i]) << "分)" << endl;
    }
}

int main() {
    vector<Student> cls;
    cls.push_back({"小明", 88, 92, 79});
    cls.push_back({"小红", 95, 81, 90});
    cls.push_back({"小刚", 70, 85, 88});

    sort(cls.begin(), cls.end(), higherFirst);   // 按总分从高到低
    printReport(cls);
    return 0;
}
text
第1名:小红(266分)
第2名:小明(259分)
第3名:小刚(243分)

每个函数只接收一个 Student 或一个 vector<Student>,参数表干干净净。数据组织好之后,程序的其余部分都变简单了——这就是本章的价值。

【跨语言对照】struct vs dict ​

本质问题:两种语言都要回答同一个问题——怎样把「一个学生的 5 项信息」捆成一包、方便地取放。C++ 的答案是结构体,Python 的答案是字典(dict)。

对比点C++ structPython dict
数据格叫什么成员键值对(键 → 值)
格子何时确定编译前写在图纸里,运行时不能加格运行中随时增删键
访问一格ming.name(点号)ming["name"](方括号加字符串键)
格子名写错了编译就报错,程序根本生成不了运行时才会暴露问题
装一群学生结构体数组字典组成的列表

等价代码:存 3 个学生的信息,打印总分最高者。

C++ 版:

cpp
#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int id;
    int chinese;
    int math;
    int english;
};

int main() {
    Student cls[3] = {
        {"小明", 1, 88, 92, 79},
        {"小红", 2, 95, 81, 90},
        {"小刚", 3, 70, 85, 88}
    };

    int best = 0;                                  // 先假设第 0 个总分最高
    for (int i = 1; i < 3; i++) {
        int ti = cls[i].chinese + cls[i].math + cls[i].english;
        int tb = cls[best].chinese + cls[best].math + cls[best].english;
        if (ti > tb) {
            best = i;                              // 发现更高的,换人
        }
    }

    int total = cls[best].chinese + cls[best].math + cls[best].english;
    cout << "总分最高的是" << cls[best].name << endl;
    cout << "总分:" << total << endl;
    return 0;
}

Python 版(详见 《Python 从入门到精通》第 12 章):

python
cls = [
    {"name": "小明", "id": 1, "chinese": 88, "math": 92, "english": 79},
    {"name": "小红", "id": 2, "chinese": 95, "math": 81, "english": 90},
    {"name": "小刚", "id": 3, "chinese": 70, "math": 85, "english": 88},
]

best = 0                                   # 先假设第 0 个总分最高
for i in range(1, 3):
    ti = cls[i]["chinese"] + cls[i]["math"] + cls[i]["english"]
    tb = cls[best]["chinese"] + cls[best]["math"] + cls[best]["english"]
    if ti > tb:
        best = i                           # 发现更高的,换人

total = cls[best]["chinese"] + cls[best]["math"] + cls[best]["english"]
print("总分最高的是" + cls[best]["name"])
print("总分:" + str(total))

两段程序的输出完全一致:

text
总分最高的是小红
总分:266

为什么设计不一样:C++ 程序在运行前要经过编译。编译器把图纸里的每一格都核对清楚,格子名写错当场报错,这让大程序里的错误很难藏到运行阶段。代价是图纸定死后,运行时不能临时加格。Python 不经过这样的编译关卡,字典的键在运行中随意增删,临时多记一项「体育分」只要一行代码。代价是键名打错不会在写程序时被发现。这是「编译期固定」与「运行期灵活」两种设计取向的差别,各有适用的场合。

下一章会看到,C++ 和 Python 都还有一种更进一步的组织方式:不只把数据打包,还把操作数据的函数也打包进去——那就是类与对象。

动手实验 ​

实验 1:给 Student 图纸加一格「体育分」pe,修改全班成绩输出程序,让每个学生打印四科总分。

💡 查看答案
cpp
#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int id;
    int chinese;
    int math;
    int english;
    int pe;          // 新增的一格
};

int main() {
    Student cls[3] = {
        {"小明", 1, 88, 92, 79, 85},
        {"小红", 2, 95, 81, 90, 78},
        {"小刚", 3, 70, 85, 88, 96}
    };

    for (int i = 0; i < 3; i++) {
        int total = cls[i].chinese + cls[i].math
                  + cls[i].english + cls[i].pe;   // 加上体育分
        cout << cls[i].name << " 四科总分:" << total << endl;
    }
    return 0;
}
text
小明 四科总分:344
小红 四科总分:344
小刚 四科总分:339

图纸加一格,初始化和计算的地方跟着加上就行。结构体内部的变化对外界的冲击被控制在一个小范围内。

实验 2:写一个函数 printStudent,接收一个 Student,打印「姓名(学号)总分」。主函数里用它打印全班。

💡 查看答案
cpp
#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int id;
    int chinese;
    int math;
    int english;
};

void printStudent(const Student& s) {   // 整个包作为参数传入
    int total = s.chinese + s.math + s.english;
    cout << s.name << "(学号" << s.id << ")总分:" << total << endl;
}

int main() {
    Student cls[3] = {
        {"小明", 1, 88, 92, 79},
        {"小红", 2, 95, 81, 90},
        {"小刚", 3, 70, 85, 88}
    };

    for (int i = 0; i < 3; i++) {
        printStudent(cls[i]);   // 一次传一包,而不是传 5 个数
    }
    return 0;
}
text
小明(学号1)总分:259
小红(学号2)总分:266
小刚(学号3)总分:243

实验 3:修改名次程序的比较规则 higherFirst,改成按数学成绩从高到低排名,预测并验证输出。

💡 查看答案
cpp
bool higherFirst(const Student& a, const Student& b) {
    return a.math > b.math;    // 只比数学
}

输出变为:

text
第1名:小明(259分)
第2名:小刚(243分)
第3名:小红(266分)

三个人的数学分是 92、85、81,所以名次是小明、小刚、小红。换一把尺子,sort 就排出另一种名次——排序算法本身一行没动。