STL之pair及其非成员函数make_pair()

std::pair是一个结构模板,提供了一种将两个异构对象存储为一个单元的方法.

定义于头文件 <utility>

1
2
3
4
template<
    class T1,
    class T2
> struct pair;

  

成员类型 Definition   成员对象 Type
first_type T1         First T1
second_type T2   Second T2

 

1
2
3
4
5
6
7
8
9
10
11
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>

1
2
3
4
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 );

  示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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的示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#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

  

posted @   zxzhang  阅读(1707)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示