std::pair是一个结构模板,提供了一种将两个异构对象存储为一个单元的方法.
定义于头文件 <utility>
template<
class T1,
class T2
> struct pair;
| 成员类型 | Definition | 成员对象 | Type | |
| first_type | T1 | First | T1 | |
| second_type | T2 | Second | T2 |
1.定义(构造):
pair<int, double> p1; //使用默认构造函数
pair<int, double> p2(1, 2.4); //用给定值初始化
pair<int, double> p3(p2); //拷贝构造函数
2.访问两个元素(通过first和second):
pair<int, double> p1; //使用默认构造函数
p1.first = 1;
p1.second = 2.5;
cout << p1.first << " " << p1.second << endl;
std::make_pair 创建一个std::pair对象,推导出目标类型的参数类型.
定义于头文件 <utility>
template< class T1, class T2 > std::pair<T1,T2> make_pair( T1 t, T2 u ); template< class T1, class T2 > std::pair<V1,V2> make_pair( T1&& t, T2&& u );
示例:
#include <iostream>
#include <utility>
#include <functional>
int main()
{
int n = 1;
int a[5] = {1,2,3,4,5};
// build a pair from two ints
auto p1 = std::make_pair(n, a[1]);
std::cout << "The value of p1 is "
<< "(" << p1.first << ", " << p1.second << ")
";
// build a pair from a reference to int and an array (decayed to pointer)
auto p2 = std::make_pair(std::ref(n), a);
n = 7;
std::cout << "The value of p2 is "
<< "(" << p2.first << ", " << *(p2.second+1) << ")
";
}
//The value of p1 is (1, 2)
//The value of p2 is (7, 2)
pair与make_pair的示例
#include<iostream>
#include<utility>
#include<string>
using namespace std;
int main ()
{
pair<string, double>product1 ("tomatoes", 3.25);
pair<string, double>product2;
pair<string, double>product3;
product2.first = "lightbulbs"; // type of first is string
product2.second = 0.99; // type of second is double
product3 = make_pair ("shoes", 20.0);
cout << "The price of " << product1.first << " is $" << product1.second << "
";
cout << "The price of " << product2.first << " is $" << product2.second << "
";
cout << "The price of " << product3.first << " is $" << product3.second << "
";
return 0;
}
//The price of tomatoes is $3.25
//The price of lightbulbs is $0.99
//The price of shoes is $20