Skip to content

20231029 - 结构体01

What is it?

结构体是 c/cpp 中的重要数据类型之一, 其由多个 "成员" 组成, 各成员可使用不同的数据类型.

定义

  • 使用 struct 关键字定义

    cpp
    // 格式
    struct <name> {
        <成员00>;
        <成员01>;
        <成员...>;
        <成员函数01>;
        <成员函数02>;
        <成员函数...>;
    };
    
    // 示例
    struct Student {
        string name;  // string 即 std::string
        char sex;
        int age;
    };
    
    Student student01;  // 定义一个 "结构实例"
    Student students[100];  // 定义一个 "结构实例" 数组, 长度 100
  • 使用 "结构实例"

    <结构实例>.<成员>[= ]

    cpp
    // student01 是 Student "结构实例"
    
    student01.name = "test"  // 设置名称
    student01.name  // 获取名称

    <结构实例>.<成员函数>()

    注意: <结构实例>.<成员函数> 不能被 = 重赋值

std::sort 函数

  • requirement / header file: #include <algorithm>
  • usage: sort(<first_pointer>, <first_pointer>+<n>, [cmp])
    • <first_pointer> 表示数组首地址, 一般为数组名
    • <n> 表示数组长度
    • [cmp] 表示排序规则(函数), 如果不传入该函数, 默认从小到大排序
    • 返回值: 排序后的数组首地址
  • 示例:
    cpp
    // a 是 数组, n 为数组长度, cmp 为排序规则(选填)
    sort(<array>, <array>+<array.length>, [cmp]);
    // 注: array.length 表示数组长度, 仅供演示, 实际数组无该属性

cmp 函数

  • 格式:
    cpp
    // type 必须为比较对象的类型
    bool <function_name>(<type> a, <type> b) {
        <比较规则>;
        // 如果返回值为 true, 则 a 在 b 前面, 否则, b 在 a 前面
    }