09-进阶算法/06-重载运算符与迭代器

来自三三百科
跳转到导航 跳转到搜索

重载运算符

C++ 允许自定义类型的运算符行为,使结构体可以直接用 +<<< 等运算符操作。

比较运算符

用于 sort 或优先队列等场景:

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()); // 按重载的 < 排序

算术运算符

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}

输入输出运算符

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 << ")";
    }
};

迭代器

迭代器是访问容器元素的通用接口。

常用迭代器操作

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 << " ";

迭代器分类

迭代器类型 支持操作 示例容器
输入/输出迭代器 读取/写入、++ istream_iterator
前向迭代器 读取、写入、++ forward_list
双向迭代器 前向 + -- listsetmap
随机访问迭代器 双向 + +n[n] vectordequestring