STL之pair及其非成员函数make_pair()
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 << ")\n";
// 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) << ")\n";
}
//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 << "\n";
cout << "The price of " << product2.first << " is $" << product2.second << "\n";
cout << "The price of " << product3.first << " is $" << product3.second << "\n";
return 0;
}
//The price of tomatoes is $3.25
//The price of lightbulbs is $0.99
//The price of shoes is $20
┆ 凉 ┆ 暖 ┆ 降 ┆ 等 ┆ 幸 ┆ 我 ┆ 我 ┆ 里 ┆ 将 ┆ ┆ 可 ┆ 有 ┆ 谦 ┆ 戮 ┆ 那 ┆ ┆ 大 ┆ ┆ 始 ┆ 然 ┆
┆ 薄 ┆ 一 ┆ 临 ┆ 你 ┆ 的 ┆ 还 ┆ 没 ┆ ┆ 来 ┆ ┆ 是 ┆ 来 ┆ 逊 ┆ 没 ┆ 些 ┆ ┆ 雁 ┆ ┆ 终 ┆ 而 ┆
┆ ┆ 暖 ┆ ┆ 如 ┆ 地 ┆ 站 ┆ 有 ┆ ┆ 也 ┆ ┆ 我 ┆ ┆ 的 ┆ 有 ┆ 精 ┆ ┆ 也 ┆ ┆ 没 ┆ 你 ┆
┆ ┆ 这 ┆ ┆ 试 ┆ 方 ┆ 在 ┆ 逃 ┆ ┆ 会 ┆ ┆ 在 ┆ ┆ 清 ┆ 来 ┆ 准 ┆ ┆ 没 ┆ ┆ 有 ┆ 没 ┆
┆ ┆ 生 ┆ ┆ 探 ┆ ┆ 最 ┆ 避 ┆ ┆ 在 ┆ ┆ 这 ┆ ┆ 晨 ┆ ┆ 的 ┆ ┆ 有 ┆ ┆ 来 ┆ 有 ┆
┆ ┆ 之 ┆ ┆ 般 ┆ ┆ 不 ┆ ┆ ┆ 这 ┆ ┆ 里 ┆ ┆ 没 ┆ ┆ 杀 ┆ ┆ 来 ┆ ┆ ┆ 来 ┆

浙公网安备 33010602011771号