pair和make_pair的主要作用都是将两个数据组合成一个数据,两个数据可以是同一个类型或者不同类型。
伪代码如下: first = pair.first second= pair.second
伪代码如下: pair <string,double> product3; product3 = make_pair ("shoes",20.0);
#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; }
// 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 std::swap(first, _Right.first); std::swap(second, _Right.second); } _Ty1 first; // the first stored value _Ty2 second; // the second stored value }; 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)); }