查看“︁03-进阶基础/04-结构体”︁的源代码
←
03-进阶基础/04-结构体
跳转到导航
跳转到搜索
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 结构体 == 结构体可以将多个不同类型的变量打包成一个新的类型。 === 定义结构体 === <syntaxhighlight lang="cpp"> struct Student { string name; int age; double score; }; </syntaxhighlight> 注意:右花括号后面要有分号。 === 使用结构体 === <syntaxhighlight lang="cpp"> Student s1; // 创建一个 Student 类型的变量 s1.name = "张三"; s1.age = 18; s1.score = 95.5; Student s2 = {"李四", 17, 88.0}; // 初始化列表 </syntaxhighlight> === 结构体访问成员 === 使用 <code>.</code> 运算符访问成员: <syntaxhighlight lang="cpp"> cout << s1.name << " " << s1.score; </syntaxhighlight> === 结构体数组 === <syntaxhighlight lang="cpp"> Student a[100]; a[0].name = "王五"; a[0].age = 19; </syntaxhighlight> === 结构体排序 === ==== 方法一:定义比较函数 ==== <syntaxhighlight lang="cpp"> struct Student { string name; int score; }; bool cmp(const Student &a, const Student &b) { return a.score > b.score; // 按分数从高到低 } // 使用 vector<Student> s(n); sort(s.begin(), s.end(), cmp); </syntaxhighlight> ==== 方法二:重载 <code><</code> 运算符 ==== <syntaxhighlight lang="cpp"> struct Student { string name; int score; bool operator<(const Student &b) const { return score > b.score; // 按分数从高到低 } }; // 使用:可以直接 sort,不需要 cmp 参数 sort(s.begin(), s.end()); </syntaxhighlight> === 结构体与 <code>typedef</code> / <code>using</code> === <syntaxhighlight lang="cpp"> typedef long long ll; // 等价于 using ll = long long; struct Point { int x, y; }; using P = Point; // 给类型起别名 </syntaxhighlight> === 结构体嵌套 === <syntaxhighlight lang="cpp"> struct Point { int x, y; }; struct Rectangle { Point topLeft; Point bottomRight; }; </syntaxhighlight> [[Category:进阶基础]] [[Category:三三文档]]
返回
03-进阶基础/04-结构体
。
导航菜单
个人工具
登录
命名空间
页面
讨论
大陆简体
查看
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
MediaWiki帮助
特殊页面
工具
链入页面
相关更改
页面信息