返回首页 C++ 模板

结构体模板

将多个不同类型的数据打包在一起——自定义数据类型

结构体 struct 成员 自定义类型 GESP4
#include <bits/stdc++.h>
using namespace std;

struct Student {
    string name;
    int age;
    double score;
};

// 带构造函数
struct Point {
    int x, y;
    Point(int x = 0, int y = 0) : x(x), y(y) {}
    double dist() { return sqrt(x*x + y*y); }
};

// 运算符重载(排序用)
struct Node {
    int val, cnt;
    bool operator<(const Node &o) const {
        return cnt != o.cnt ? cnt > o.cnt : val < o.val;
    }
};

int main() {
    Student s1 = {"小明", 12, 95.5};
    cout << s1.name << " " << s1.score << endl;

    Student stu[100];
    int n; cin >> n;
    for (int i = 0; i < n; i++)
        cin >> stu[i].name >> stu[i].age >> stu[i].score;

    // 按分数排序
    sort(stu, stu + n, [](const Student &a, const Student &b) {
        return a.score > b.score;
    });

    Point p(3, 4);
    cout << p.dist() << endl;  // 5

    return 0;
}

📖 要点说明

⚠️ 常见错误