码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-05-01 00:23:49      阅读:382      评论:0      收藏:0      [点我收藏+]

标签:std   构造函数   end   默认构造函数   创建   class   space   mic   ring   

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

  

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

标签:std   构造函数   end   默认构造函数   创建   class   space   mic   ring   

原文地址:http://www.cnblogs.com/zzy19961112/p/6790740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!