代码示例:
#include<iostream> #include<string> #include<utility> using namespace std; void f(pair<int,const char*>a) { cout<<a.first<<" "<<a.second<<endl; } void g(pair<int,string>a) { a.first+=1; cout<<a.first<<" "<<a.second<<endl; } void foo() { pair<int,const char*> p(42,"hello"); f(p); g(p);//template 构造函数隐式转换 cout<<p.first<<" "<<p.second<<endl; } int main() { //定义 pair<int,string> s(100,"xiaoming"),str; cout<<s.first<<" "<<s.second<<endl; str=s; cout<<str.first<<" "<<str.second<<endl; //多个形式相同的pair typedef pair<int,string> author; author a(101,"lanzhihui"); author b(102,"wangdan"); author c; c=make_pair(103,"wangqian"); cout<<a.first<<" "<<a.second<<endl; cout<<b.first<<" "<<b.second<<endl; cout<<c.first<<" "<<c.second<<endl; //template形式的构造函数 foo(); system("pause"); return 0; }运行结果:
实现pair内部如何实现?
#include<string> #include<iostream> using namespace std; template <class T1,class T2> struct my_pair { typedef T1 first_type; typedef T2 second_type; T1 first; T2 second; //默认构造函数 my_pair() :first(T1()),second(T2()) {} //T1()用0初始化 T2()用0初始化 //构造函数 my_pair(const T1&a,const T2&b) :first(a),second(b) {} //拷贝构造函数 template<class U,class V> my_pair(const my_pair<U,V>&p) :first(p.first),second(p.second) {cout<<"a"<<endl;}//{用来测试那些对象创建调用了copy构造函数} }; //比较 template<class T1,class T2> bool operator==(const my_pair<T1,T2>&s1,const my_pair<T1,T2>&s2) { return s1.first==s2.first&&s1.second==s2.second; } template<class T1,class T2> bool operator>(const my_pair<T1,T2>&s1,const my_pair<T1,T2>&s2) { return (s1.first>s2.first)||(!(s1.first<s2.first)&&s1.second>s2.second); } template<class T1,class T2> bool operator<(const my_pair<T1,T2>&s1,const my_pair<T1,T2>&s2) { return (s1.first<s2.first)||(!(s1.first>s2.first)&&s1.second<s2.second); } int main() { //默认构造函数 my_pair<int,string> a2; cout<<"默认构造函数:"<<endl; cout<<a2.first<<" "<<a2.second<<endl; //构造函数 my_pair<int,char*> a1(101,"lanzhihui");//参数类型必须与定义类型一样 cout<<"构造函数:"<<endl; cout<<a1.first<<" "<<a1.second<<endl; my_pair<int,char*> a3(101,"laznzhihui"); cout<<a3.first<<" "<<a3.second<<endl; //拷贝构造函数 my_pair<int,string> s1(a1),s2(a1);//使用Template形式的copy构造函数,构造过程隐式类型转换 cout<<"拷贝构造函数:"<<endl; cout<<s1.first<<" "<<s1.second<<endl; cout<<s2.first<<" "<<s2.second<<endl; my_pair<int,string> s3; cout<<"sss"<<endl; s3=a3;//也是调用拷贝构造函数 cout<<s3.first<<" "<<s3.second<<endl; cout<<"sss"<<endl; cout<<"测试:"<<endl; //测试'==' '>' '<' if(s1==s2) { cout<<"operator== OK!"<<endl; } if(s1<s3) { cout<<"operator> OK!"<<endl; } if(s3>s1) { cout<<"operator< OK!"<<endl; } system("pause"); return 0; }