c++中的ignore和tie

220 篇文章 28 订阅

一、tie和ignore

std::tie和std::ignore都是定义在< tuple >这个头文件中的,意思其实就很明了了,它肯定是辅助tuple这个数据结构的,先看一下它们的具体定义:
具体的定义:

//Defined in header <tuple>
const /*unspecified*/ ignore;
(since C++11)
(until C++17)
inline constexpr /*unspecified*/ ignore;
(since C++17)

template< class... Types >
std::tuple<Types&...> tie( Types&... args ) noexcept;
(since C++11)
(until C++14)
template< class... Types >
constexpr std::tuple<Types&...> tie( Types&... args ) noexcept;
(since C++14)

std::tie其实是“Creates a tuple of lvalue references to its arguments or instances of std::ignore.”利用参数或者std::ignore创建一个元组的左值引用,它可以用来对tuple的解包或者引入相关的字典排序数据。而std::ignore其实就类似于Go或者其它语言中的忽略元素,起到一个点位符的作用。

二、例程

说还是没有什么说服力,看看简单的例程就会明白这两个数据结构的用法:

#include <iostream>
#include <string>
#include <set>
#include <tuple>
 
struct S {
    int n;
    std::string s;
    float d;
    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);
 
    if (inserted)
        std::cout << "Value was inserted successfully\n";
}

再看看ignore的例程:

#include <iostream>
#include <string>
#include <set>
#include <tuple>
 
[[nodiscard]] int dontIgnoreMe()
{
    return 42;
}
 
int main()
{
    std::ignore = dontIgnoreMe();
 
    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\n";
    }
}

"nodiscard"的意思是说这个返回值是需要应用的,不能舍弃的,换句话说,如果这个函数的返回值没有被使用,编译器会发出警告。set_of_str.insert()这个函数需要注意的是可能返回std::pair也可能返回其它,而这里正好是使用pair到tie的转换,然后忽略了返回的迭代器,而只关心成功与否。前面提到过,pair可以理解成tuple的特殊情况,这样对上面这个例程就会很清晰的理解了。而std::ignore可以根据实际情况对返回的相关tuple的内容进行选择性的忽略,这就是它的优势所在。

三、总结

其实越深入发现STL中的内容,有好多东西都已经写好,不用自己在编程时再进行处理。可实际情况可以说各种环境都有,程序员对STL的掌握和应用的熟练程度也不尽相同,这就导致有些STL封装好的数据结构和算法其实是没有用到。这还得需要根据自己的实际情况来取舍,能省点事儿,省点儿还是好的。
努力要从今日始!
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值