> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/data-structures/struct.md).

# 结构体

### 定义与使用

结构体把**不同类型**的数据组合成一个整体。

```cpp
struct Student {
    string name;
    int score;
    double height;
};

Student s;
s.name = "Tom";
s.score = 95;
```

### 初始化

```cpp
Student a = {"Tom", 95, 1.72};
Student b{"Jerry", 88, 1.65};   // C++11
Student c = {};                  // 全部置零 / 空
```

### 结构体数组

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

### 结构体指针

```cpp
Student s{"Tom", 95};
Student *p = &s;
cout << p->name;   // 用 -> 访问成员
```

### 结构体嵌套

```cpp
struct Point { int x, y; };
struct Rect { Point tl, br; };
Rect r{{0, 0}, {10, 5}};
cout << r.br.x;   // 10
```

### 结构体作为函数参数

值传递会复制整个结构体，建议用**引用**：

```cpp
void print(const Student &s) {   // const 引用，不复制也不修改
    cout << s.name << " " << s.score;
}
```

### 结构体排序

```cpp
bool cmp(const Student &a, const Student &b) {
    if (a.score != b.score) return a.score > b.score;  // 分数降序
    return a.name < b.name;                            // 分数相同按名字升序
}
sort(list, list + n, cmp);
```

> 考纲还要求掌握：结构体数组、结构体指针、结构体嵌套结构体、结构体做函数参数、const 使用场景。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/data-structures/struct.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
