1. 程式人生 > >C++ pair的用法例項詳解(結構體模板應用初探)

C++ pair的用法例項詳解(結構體模板應用初探)

1 pair的應用(結構體模板)

pair是將2個數據組合成一個數據,當需要這樣的需求時就可以使用pair,如stl中的map就是將key和value放在一起來儲存。另一個應用是,當一個函式需要返回2個數據的時候,可以選擇pair。

標頭檔案:#include<utility>

類模板:template <class T1, class T2> struct pair

定義方法:

    pair<變數型別1,變數型別2> 變數名

eg:  pair<int,int>p;

.例項化

eg:pair<int,int>(3,4)//初始化一個pair,第一個成員是int,第二個成員也是int型別

物件的賦值以及make_pair()的應用:

pair<int,int>q=make_pair(3,4);

(1)第一種用法函式返回:

pair<int,int>func()
{
intheight=3;
intweight=4;
returnpair<int,int>(3,4);
}
intmain(intargc,char*argv[])
{
pair<int,int>p=func(); //呼叫函式
return0;
}
cout<<p.first<<""<<p.second<<endl; //

(2)使用在stl map

struct
student{
intheight;
intweight;
};
intmain(intargc,char*argv[])
{
map<int,structstudent>map1;
structstudenta;
structstudentb;
    //錯誤寫法 map.insert<1,a>;錯誤寫法
map1.insert(pair<int,structstudent>(1,a));//等價於 ----- map1.insert(make_pair(1,a));
cout<<map1.size()<<endl;
return0;
}

3.pair中元素的訪問(first & second):

    eg:

pair<int,int>func()
{
intheight=3;
intweight=4;
returnpair<int,int>(3,4);
}
pair<int,int>p=func();
cout<<p.first<<""<<p.second<<endl;

說到這裡,有的同學應該想問,這不就是c語言的結構體嗎?是的,這就是c++的結構體模板

原始碼:

template<class_T1,class_T2>
structpair
{
typedef_T1first_type;///@cfirst_typeisthefirstboundtype
typedef_T2second_type;///@csecond_typeisthesecondboundtype
_T1first;///@cfirstisacopyofthefirstobject
_T2second;///@csecondisacopyofthesecondobject、
....
    .......對了什麼叫結構體模板,哈哈,敬請關注!!!