stl之pair简介

原载:http://hi.baidu.com/taozpwater/item/d85d81bde4fd154b2bebe34e

1、简介

        class pair ,中文译为对组,可以将两个值视为一个单元。对于map和multimap,就是用pairs来管理value/key的成对元素。任何函数需要回传两个值,也需要pair。

        该函数的相关内容如下所示:

        |->Type----->struct

        |->Include---> <utility>

        |->Define----> pair<calss first,calss second>(first,second)

        |

        |->member

        |      |------>first

        |      |------>second

        |

        |->Sub

        |      |------>constructor(default,assignment,copy)

        |

        |->Fun

        |------>operator(==,<,<=,>,>=,!=,=)

        |------>make_pair(first,second) 返回一个新的pair

     需求:

      Header: <utility>

      Namespace: std

 

2、stl源码

pair的源码

 


// TEMPLATE STRUCT pair

template<class _Ty1,

    class _Ty2> struct pair

    {// store a pair of values

    typedef pair<_Ty1, _Ty2> _Myt;

    typedef _Ty1 first_type;

    typedef _Ty2 second_type;

    pair()

        : first(_Ty1()), second(_Ty2())

        {// construct from defaults

        }

 

    pair(const _Ty1& _Val1, const _Ty2& _Val2)

        : first(_Val1), second(_Val2)

        {// construct from specified values

        }

 

    template<class _Other1,

        class _Other2>

        pair(const pair<_Other1, _Other2>& _Right)

        : first(_Right.first), second(_Right.second)

        {// construct from compatible pair

        }

 

    void swap(_Myt& _Right)

        {// exchange contents with _Right

        if (this != &_Right)

            {// different, worth swapping

            std::swap(first, _Right.first);

            std::swap(second, _Right.second);

            }

        }

    _Ty1 first;// the first stored value

    _Ty2 second;// the second stored value

    };




makepair的源码


template<class _Ty1,

    class _Ty2> inline

    pair<_Ty1, _Ty2> make_pair(_Ty1 _Val1, _Ty2 _Val2)

    {// return pair composed from arguments

    return (pair<_Ty1, _Ty2>(_Val1, _Val2));

    }



3、使用范例

#include <utility> 

#include <stdio.h>

using namespace std;

int main() 

    pair<char, int> c1(L'x', 3); 

    printf("[%c, %d", c1.first, c1.second); 

 

    c1 = make_pair(L'y', 4); 

    printf("[{%c}, {%d}]", c1.first, c1.second); 

    return (0); 

}



posted on 2012-07-11 15:35  青色有角三倍速  阅读(198)  评论(0编辑  收藏  举报