STL通用工具--Pairs

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 values
pair(const T1& a, const T2& b) : first(a), second(b)
{ }

// copy constructor with implicit conversions
template<class U, class V> pair(const pair<U,V>& p) : first(p.first), second(p.second)
 {   }
};

// comparisons
template <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 pair
template <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 values
template <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 pair
g(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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值