标签:font clu value air for 比较 rgs element 占位符
一个未指定的类型对象,任何值都可以没有影响地赋值给它。通常使用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\n";
}
return 0;
}
创建一个元组的左值引用
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\n";
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) 在前面
标签:font clu value air for 比较 rgs element 占位符
原文地址:https://www.cnblogs.com/zuofaqi/p/10211507.html