STL通用工具--Pairs

    技术2022-05-11  75

    Pairs class pair 可以将两个值视为一个单元。对于 map multimap ,就是用 pairs 来管理 value/key 的成对元素。任何函数需要回传两个值,也需要 pair pair 结构定义在 <utility> 里面: 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; /* default constructor T1() and T2() force initialization for built-in types*/ pair(): first(T1()), second(T2()) {        } // constructor for two valuespair(const T1& a, const T2& b) : first(a), second(b) { } // copy constructor with implicit conversionstemplate<class U, class V> pair(const pair<U,V>& p) : first(p.first), second(p.second)  {   }}; // comparisonstemplate <class T1, class T2> bool operator== (const pair<T1,T2>&, const pair<T1,T2>&);template <class T1, class T2> bool operator< (const pair<T1,T2>&, const pair<T1,T2>&);... // similar: !=, < =, > , > =   // convenience function to create a pairtemplate <class T1, class T2> pair<T1,T2> make_pair (const T1&, const T2&);} 这里, pair 被定义为 struct ,而不是 class ,所有的成员都是 public ,可以直接存取 pair 中的个别值。 两个 pairs 互相比较的时候,第一个元素具有较高的优先权,和 str 的比较差不多啦。 关于 make_pair()template 函数 make_pair() 是无需写出类型,就可以生成一个 pair 对象。 namespace std {// create value pair only by providing the valuestemplate <class T1, class T2>pair<T1,T2> make_pair (const T1& x, const T2& y) {return pair<T1,T2>(x, y);}} 例如,你可以这样使用 make_pair() std::make_pair(42,'@') 而不必费力: std::pair<int,char>(42,'@') 当我们有必要对一个接受 pair 参数的函数传递两个值的时候, make_pair() 就方便多了: void f(std::pair<int,const char*>);void g(std::pair<const int,std::string>);...void foo {f(std::make_pair(42,"hello")); // pass two values as pairg(std::make_pair(42,"hello")); // pass two values as pair// with type conversions}   map 中,元素的储存大都是 key/value 形式的,而且 stl 中,凡是 必须传回两个值 得函数,都会用到 pair. 比如下面的实例: 运用 pair()std::map<std::string,float> coll;...// use implicit conversion:coll.insert(std::pair<std::string,float>("otto",22.3));// use no implicit conversion:coll.insert(std::pair<const std::string,float>("otto",22.3)); 运用 make_pair()std::map<std::string,float> coll;...coll.insert(std::make_pair("otto",22.3));    

    最新回复(0)