c++ 让 std::pair 更好看

pair 的 first 和 second 真的很丑,那么能不能对其进行重命名呢?
答案是没问题,我们通过引用实现之。

pair 的头文件 <utility>

版本 1

最省略写法:

#include <iostream>
#include <utility>

using namespace std;

struct Node : public std::pair<int, int> {
    int &x = first;
    int &y = second;
    // explicit Node() = default;
    // virtual ~Node() = default;
    // Node(const Node &) = default;
    // Node &operator=(const Node &) = delete;
};

int main() {
    Node tmp;
    cout << tmp.x << endl
         << tmp.y;
}

注释掉的部分便是 c++11 对其的处理方式,你不用写出来。

优点:写的内容很少
缺点:只能默认构造,之后再赋值

版本 2

多写一点:

#include <iostream>
#include <utility>

using namespace std;

struct Node : public std::pair<int, int> {
    int &x = first;
    int &y = second;
    explicit Node() = default;
    virtual ~Node() = default;
    Node(const Node &) = default;
    Node &operator=(const Node &) = delete;
    Node(const pair<int, int> &arg) : x(first), y(second), pair(arg) {}
};

int main() {
    Node tmp(make_pair(1, 2));
    cout << tmp.x << endl
         << tmp.y;
}

我们加入传入父类的构造函数,使其可以通过 pair 的构造函数而进行初始化

优点:能进行初始化
缺点:有构造临时 pair 的时间开销,不能拷贝赋值

版本 3

再多写一些:

#include <iostream>
#include <utility>

using namespace std;

struct Node : public std::pair<int, int> {
    int &x = first;
    int &y = second;
    explicit Node() = default;
    virtual ~Node() = default;
    Node(const Node &) = default;
    Node &operator=(const Node &) = delete;
    Node(const pair<int, int> &arg) : x(first), y(second), pair(arg) {}
    Node(int argx, int argy) : x(first), y(second), pair(argx, argy) {}
};

int main() {
    Node tmp(1, 2);
    cout << tmp.x << endl
         << tmp.y;
}

我们只传入数值,并使用 pair 的构造函数

优点:同版本2
缺点:不能拷贝赋值

最终版

#include <iostream>
#include <utility>

using namespace std;

struct Node : public std::pair<int, int> {
    int &x = first;
    int &y = second;
    explicit Node() = default;
    virtual ~Node() = default;
    Node(const Node &) = default;
    Node &operator=(const Node &arg) { return x = arg.x, y = arg.y, *this; }
    Node(const pair<int, int> &arg) : x(first), y(second), pair(arg) {}
    Node(int argx, int argy) : x(first), y(second), pair(argx, argy) {}
};

int main() {
    Node tmp(1, 2);
    Node tmp2 = tmp;
    cout << tmp2.x << endl
         << tmp2.y;
}

缺点:无

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

岚花落_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值