一、tuple元组
1.1、简介
C++11 标准新引入了一种类模板,命名为 tuple(元组)。tuple 最大的特点是:实例化的对象可以存储任意数量、任意类型的数据。
1.2、初始化
tuple 本质是一个以可变模板参数定义的类模板,它定义在
#include <tuple>
实例化 tuple 模板类对象常用的方法有两种,一种是借助该类的构造函数,另一种是借助 make_tuple() 函数。
- 类的构造函数
tuple 模板类提供有很多构造函数,包括:
1) 默认构造函数
constexpr tuple();
2) 拷贝构造函数
tuple (const tuple& tpl);
3) 移动构造函数
tuple (tuple&& tpl);
4) 隐式类型转换构造函数
template <class... UTypes>
tuple (const tuple<UTypes...>& tpl); //左值方式
template <class... UTypes>
tuple (tuple<UTypes...>&& tpl); //右值方式
5) 支持初始化列表的构造函数
explicit tuple (const Types&... elems); //左值方式
template <class... UTypes>
explicit tuple (UTypes&&... elems); //右值方式
6) 将pair对象转换为tuple对象
template <class U1, class U2>
tuple (const pair<U1,U2>& pr); //左值方式
template <class U1, class U2>
tuple (pair<U1,U2>&& pr); //右值方式
举个例子:
#include <iostream> // std::cout
#include <tuple> // std::tuple
using std::tuple;
int main()
{
std::tuple<int, char> first; // 1) first{}
std::tuple<int, char> second(first); // 2) second{}
std::tuple<int, char> third(std::make_tuple(20, 'b')); // 3) third{20,'b'}
std::tuple<long, char> fourth(third); // 4)的左值方式, fourth{20,'b'}
std::tuple<int, char> fifth(10, 'a'); // 5)的右值方式, fifth{10.'a'}
std::tuple<int, char> sixth(std::make_pair(30, 'c')); // 6)的右值方式, sixth{30,''c}
return 0;
}
- make_tuple()函数
上面程序中,我们已经用到了 make_tuple() 函数,它以模板的形式定义在头文件中,功能是创建一个 tuple 右值对象(或者临时对象)。
对于 make_tuple() 函数创建了 tuple 对象,我们可以上面程序中那样作为移动构造函数的参数,也可以这样用:
auto first = std::make_tuple (10,'a'); // tuple < int, char >
const int a = 0; int b[3];
auto second = std::make_tuple (a,b); // tuple < int, int* >
程序中分别创建了 first 和 second 两个 tuple 对象,它们的类型可以直接用 auto 表示。
1.3、访问
- 用get标准库模板进行访问其元素内容
- 用tuple_size访问其元素个数
- 用tuple_element访问其元素类型
#include<iostream>
#include<string>
#include<tuple>
using namespace std;
int main()
{
auto t1 = make_tuple(1, 2, 3, 4.4);
cout << "第1个元素:" << get<0>(t1) << endl;//和数组一样从0开始计
cout << "第2个元素:" << get<1>(t1) << endl;
cout << "第3个元素:" << get<2>(t1) << endl;
cout << "第4个元素:" << get<3>(t1) << endl;
typedef tuple<int, float, string>TupleType;
cout << tuple_size<TupleType>::value << endl;
tuple_element<1, TupleType>::type fl = 1.0;
return 0;
}
输出结果:
第1个元素:1
第2个元素:2
第3个元素:3
第4个元素:4.4
3
二、pair比较
三、lower_bound和upper_bound
资料:
https://deepinout.com/cpp/cpp-questions/g_how-to-declare-comparator-for-set-of-pair-in-cpp.html
https://c.biancheng.net/view/8600.html
https://blog.csdn.net/qq_37529913/article/details/125139815
- bound lower_bound upper_bound tuple lowerbound lower_bound upper_bound lower bound lower_bound upper_bound tuple bound upper_bound lower_bound upper bound lower_bound upper_bound函数 bound lower_bound upper_bound常见 bound写法lower_bound upper_bound lower_bound upper_bound语法 笔记lower lower_bound模版lower bound upper_bound