C++中的pair对组

    xiaoxiao2021-12-10  18

    pair将两个值视为一个单元,使用pair可以来管理键值/实值(key/value)的成对元素。 pair实现的简易代码:

    #include <iostream> #include <string> #include <cstring> using namespace std; template <class T1,class T2> struct Pair{ //type names for the values; typedef T1 first_type; typedef T2 second_type; //member T1 first; T2 second; Pair():first(T1()),second(T2()){ } //constructor for two values Pair(const T1& a,const T2& b) :first(a),second(b){ } //copy constructors template<class U,class V> Pair(const Pair<U,V>& p) : first(p.first),second(p.second){ } }; //creat a pair function template <class T1,class T2> Pair<T1,T2> make_Pair(const T1& x,const T2 & y){ return Pair<T1,T2>(x,y); } template <class T1,class T2> bool operator<(const Pair<T1,T2>& x, const Pair<T1,T2>& y) { return x.first<y.first ||(!(y.first<x.first)&& x.second<y.second); } template <class T1,class T2> void show(const Pair<T1,T2>& x){ cout<<x.first<<","<<x.second<<endl; } int main() { Pair<int,string> a(1,"string"),b1(a); show(a); show(b1); string s="Hebe"; show(make_Pair(1,s)); pair<int,string> b(2,"world"); cout<<b.first<<","<<b.second<<endl; }

    注意, pair被定义为struct,而不是class,所有的成员都是public。

    pair的比较 两个pair比较时,第一元素具有较高的优先级,当第一元素相等时,才继续比较第二元素。

    pair的定义使用

    pair<int,string> a(1,"str"); //便捷的make_pair make_pair(42,'@');//等价于pair<int,char>(42,'@'); cout<<a.first<<a.second;

    C++标准程序库中运用了大量的pair,如map,multimap容器的函数类型就是pair。

    转载请注明原文地址: https://ju.6miu.com/read-700402.html

    最新回复(0)