8

c++11的 元组(tuple)有什么用?有什么使用场景?

 3 years ago
source link: https://www.zhihu.com/question/455522367/answer/1845218041
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

c++11的 元组(tuple)有什么用?有什么使用场景?

c++11中的tuple(元组)实际上有什么用?其内存结构形如一个结构体,如: tuple<int,float,int,float> tu…
22
3,104
登录一下,更多精彩内容等你发现
贡献精彩回答,参与评论互动
C++程序猿, 公众号:高级开发者

给自定义结构体、类实现比较操作符时

struct S {
    int n;
    std::string s;
    float d;
    bool operator<(const S& rhs) const {
        return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);
    }
};

上述代码会优先按照第一个字段n进行比较,相等的话进而判断第二个字段,最后到第三个字段,直到能够获得比较的结果为止。

std::tie会将函数参数打包成元组,根据元组自身的比较性质进行比较

另外返回类型、函数入参用元组并不是什么好的模式,字段一多的时候可读性不如结构体


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK