查看“︁09-进阶算法/06-重载运算符与迭代器”︁的源代码
←
09-进阶算法/06-重载运算符与迭代器
跳转到导航
跳转到搜索
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 重载运算符 == C++ 允许自定义类型的运算符行为,使结构体可以直接用 <code>+</code>、<code><</code>、<code><<</code> 等运算符操作。 === 比较运算符 === 用于 <code>sort</code> 或优先队列等场景: <syntaxhighlight lang="cpp"> struct Student { string name; int score, age; // 按分数降序,分数相同按年龄升序 bool operator<(const Student& that) const { if (score != that.score) return score < that.score; return age < that.age; } }; vector<Student> v; sort(v.begin(), v.end()); // 按重载的 < 排序 </syntaxhighlight> === 算术运算符 === <syntaxhighlight lang="cpp"> struct Point { int x, y; Point operator+(const Point& that) const { return {x + that.x, y + that.y}; } Point operator-(const Point& that) const { return {x - that.x, y - that.y}; } }; Point a{1, 2}, b{3, 4}; Point c = a + b; // {4, 6} </syntaxhighlight> === 输入输出运算符 === <syntaxhighlight lang="cpp"> struct Point { int x, y; friend istream& operator>>(istream& in, Point& p) { return in >> p.x >> p.y; } friend ostream& operator<<(ostream& out, const Point& p) { return out << "(" << p.x << ", " << p.y << ")"; } }; </syntaxhighlight> == 迭代器 == 迭代器是访问容器元素的通用接口。 === 常用迭代器操作 === <syntaxhighlight lang="cpp"> vector<int> v = {1, 2, 3, 4, 5}; vector<int>::iterator it; for (it = v.begin(); it != v.end(); it++) cout << *it << " "; // C++11 auto 简化 for (auto it = v.begin(); it != v.end(); it++) cout << *it << " "; // 范围 for 循环 for (int x : v) cout << x << " "; </syntaxhighlight> === 迭代器分类 === {| class="wikitable" ! 迭代器类型 !! 支持操作 !! 示例容器 |- | 输入/输出迭代器 | 读取/写入、<code>++</code> | <code>istream_iterator</code> |- | 前向迭代器 | 读取、写入、<code>++</code> | <code>forward_list</code> |- | 双向迭代器 | 前向 + <code>--</code> | <code>list</code>、<code>set</code>、<code>map</code> |- | 随机访问迭代器 | 双向 + <code>+n</code>、<code>[n]</code> | <code>vector</code>、<code>deque</code>、<code>string</code> |} [[Category:进阶算法]] [[Category:三三文档]]
返回
09-进阶算法/06-重载运算符与迭代器
。
导航菜单
个人工具
登录
命名空间
页面
讨论
大陆简体
查看
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
MediaWiki帮助
特殊页面
工具
链入页面
相关更改
页面信息