概述
功能:将两个value看作一个单元
头文件:
#include <utility>
访问成员
直接访问对应数据成员
为了让程序能够处理pair的两个值,它提供了“直接访问对应数据成员”的能力。所以pair定义成了一个struct,而不是一个class,因此所有的成员都是public:
template<class _T1, class _T2>
struct pair
{
typedef _T1 first_type; /// @c first_type is the first bound type
typedef _T2 second_type; /// @c second_type is the second bound type
_T1 first; /// @c first is a copy of the first object
_T2 second; /// @c second is a copy of the second object
看个使用例子:下面功能是将一个pair写到一个stream内:
std::tuple_size<>::value:获得元素个数
std::tuple_element<>::type:获得元素类型
std::get()获取first或者second
构造函数
默认构造函数会调用元素的默认构造函数来初始化值
std::pair<int, float> p; // 默认调用int(), float()初始化p中的元素
拷贝构造函数同时存在两个版本:
- 版本一: 接受相同类型的pair
- 版本二:是一个memeber template,在“构造函数需要隐式转换”时调用。如果pair对象被复制,调用的是版本2
#include <utility>
#include <string>
void f(std::pair<int, const char*>){};
void g(std::pair<const int, std::string>){};
int main()
{
std::pair<int, const char*> p(42, "hello world");
f(p); // OK: calls implicittly generated copy
g(p); // OK: calls template constructor
}
辅助函数:make_pair()
一般性用法
std::pair<int, char>(42, '@');
相当于:
make_pair(42, '@');
我们经常这么使用:
#include <utility>
#include <string>
void f(std::pair<int, const char*>){};
void g(std::pair<const int, std::string>){};
int main()
{
f(std::make_pair(42, "hello aaa"));
g(std::make_pair(42, "hello world"));
}
还可以使用`{}`来简化操作
#include <utility>
#include <string>
void f(std::pair<int, const char*>){};
void g(std::pair<const int, std::string>){};
int main()
{
f({42, "hello world"});
g({42, "hello world"});
}
移动语义与引用语义
#include <utility>
#include <string>
#include <functional>
int main()
{
int i = 0;
auto p = std::make_pair(std::ref(i), std::ref(i)); // 引用类型
++p.first;
++p.second;
printf("i = %d\n", i);
int i1 = 0;
auto p1 = std::make_pair(std::move(i1), std::move(i1));
++p1.first;
++p1.second;
printf("i1 = %d\n", i1);
}
tie:抽取出pair中的value
感觉没啥用
#include <utility>
#include <string>
#include <functional>
void f(std::pair<int, const char*>){};
void g(std::pair<const int, std::string>){};
int main()
{
int i = 0;
auto p = std::make_pair('x', 'y');
char c;
std::tie(std::ignore, c) = p; //ignore one, ref two
printf("%c\n", c); // y
p.second = 'a';
printf("%c, %c\n", c, p.second ); // y, a
}
5、元祖与元祖中的元素
#include <iostream>
#include <utility>
#include <tuple>
using namespace std;
class Foo {
public:
Foo (tuple<int, float>) {
cout << "Foo::Foo(tuple)" << endl;
}
template <typename... Args>
Foo (Args... args) {
cout << "Foo::Foo(args...)" << endl;
}
};
int main()
{
// create tuple t:
tuple<int,float> t(1,2.22);
// 将元组作为一个整体传递给Foo的构造函数:
pair<int,Foo> p1 (42, t);
// 将元组的元素传递给Foo的构造函数:
pair<int,Foo> p2 (piecewise_construct, make_tuple(42), t);
}