1、tuple应用:
解释:是一个元组,可包含无限多不同类型变量,pair的升级版,但没有pair得成员变量first、second。
1.1、代码:
// tuple example
#include <iostream> // std::cout
#include <tuple> // std::tuple, std::get, std::tie, std::ignore
int main ()
{
std::tuple<int,char> foo (10,'x'); // 构造tuple
auto bar = std::make_tuple ("test", 3.1, 14, 'y');
std::get<2>(bar) = 100; //通过下标获取元素
int myint; char mychar;
std::tie (myint, mychar) = foo; // unpack elements
std::tie (std::ignore, std::ignore, myint, mychar) = bar; // unpack (with ignore)
mychar = std::get<3>(bar);
std::get<0>(foo) = std::get<2>(bar); //通过下标获取元素
std::get<1>(foo) = mychar;
std::cout << "foo contains: ";
std::cout << std::get<0>(foo) << ' ';
std::cout << std::get<1>(foo) << '\n';
return 0;
}
用法:初始化tuple实例后,通过std::tie
解包元素,利用std::ignore
忽略指定元素,通过std::get获取指针位置元素。
参考资料:
1、 tuple、tie与ignore学习链接
2、C++ tuple元组的基本用法(总结)
2、std::tie用法:
解释:可以用于解包tuple元素;其构造函数返回一个元组。
代码:
1、std::tie(a,b,c) = std::tuple<int,int,double>(1,2,4.1); // 用于解包tuple
2、std::tuple<int, int, double> pu = std::tie(a,b,c); // 创建到其参数或 std::ignore 实例的左值引用的tuple。
3、std::tie(a, b) = std::make_tuple(2, 3);
解释:
代码行1:tie用以解包元组,获取元组中元素值;
代码行2:tie构造返回的是一个元组。
用法:用于结构体大小比较:
struct S {
int n;
std::string s;
float d;
bool operator<(const S& rhs) const
{
// 比较 n 与 rhs.n,
// 然后为 s 与 rhs.s,
// 然后为 d 与 rhs.d
return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);
}
};
参考资料:
解包tuple:http://www.cplusplus.com/reference/tuple/tie/
tie用于struct比较:https://zh.cppreference.com/w/cpp/utility/tuple/tie
3、Pair:
代码:
// pair::pair example
#include <utility> // std::pair, std::make_pair
#include <string> // std::string
#include <iostream> // std::cout
int main () {
std::pair <std::string,double> product1; // default constructor
std::pair <std::string,double> product2 ("tomatoes",2.30); // value init
std::pair <std::string,double> product3 (product2); // copy constructor
product1 = std::make_pair(std::string("lightbulbs"),0.99); // using make_pair (move)
product2.first = "shoes"; // the type of first is string
product2.second = 39.90; // the type of second is double
std::cout << "The price of " << product1.first << " is $" << product1.second << '\n';
std::cout << "The price of " << product2.first << " is $" << product2.second << '\n';
std::cout << "The price of " << product3.first << " is $" << product3.second << '\n';
return 0;
}
参考资料:std::pair::pair