zoukankan      html  css  js  c++  java
  • c++ tie,ignore

    ignore

    一个未指定的类型对象,任何值都可以没有影响地赋值给它。通常使用tie来解压一个元组,作为可以忽略的占位符。

    #include <iostream>
    #include <string>
    #include <set>
    #include <tuple>
     
    int main()
    {
        std::ignore = 9;
        std::ignore = "hello";
        std::ignore = std::make_pair<int,std::string>(8, "23");
    
        std::set<std::string> set_of_str;
        bool inserted = false;
        std::tie(std::ignore, inserted) = set_of_str.insert("Test");
        if (inserted)
        {
            std::cout << "Value was inserted successfully
    ";
        }
    
        return 0;
    }

    tie

    创建一个元组的左值引用

    template<typename... _Elements>
    constexpr tuple<_Elements&...>
    tie(_Elements&... __args) noexcept
    {
        return tuple<_Elements&...>(__args...);
    }

    可以看到,tie函数返回的是一个tuple的左值引用

    tie函数可以用来解压一个pair,tuple,也可以用来产生一个结构体的字典序比较

    #include <iostream>
    #include <string>
    #include <set>
    #include <tuple>
    #include <algorithm>
     
    struct S {
        int n;
        std::string s;
        float d;
    
        S(int in, std::string && ss, float fd):n(in),s(ss),d(fd)
        {}
    
        bool operator<(const S& rhs) const
        {
            // compares n to rhs.n,
            // then s to rhs.s,
            // then d to rhs.d
            return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);
        }
    };
     
    int main()
    {
        std::set<S> set_of_s; // S is LessThanComparable
     
        S value {42, "Test", 3.14};
        std::set<S>::iterator iter;
        bool inserted;
     
        // unpacks the return value of insert into iter and inserted
        std::tie(iter, inserted) = set_of_s.insert(value);
        set_of_s.emplace(12,"t2", 9.8);
     
        if (inserted)
            std::cout << "Value was inserted successfully
    ";
    
        for_each(set_of_s.begin(), set_of_s.end(), [](const S & value){
            std::cout << value.n << ' ' << value.s << ' ' << value.d << std::endl;
        });
    
        return 0;
    }

    输出:

    Value was inserted successfully
    12 t2 9.8
    42 Test 3.14

    经过排序之后,(12,"t2", 9.8) 在前面

  • 相关阅读:
    归并排序
    CTE 递归
    Cordova 入门文档
    Javascript 原型链
    Windows11 正式版偷渡开启安卓子系统
    快速解决gerrit merge confict问题
    利用VPS来搭建个人主页
    检测串行序列10010
    Verilog语法总结
    深度学习中常见优化算法学习笔记
  • 原文地址:https://www.cnblogs.com/zuofaqi/p/10211507.html
Copyright © 2011-2022 走看看