首页 > 代码库 > STL之Pairs
STL之Pairs
什么是Pair
关于类Pair的介绍,下面是引自《C++ Standard Library》的一段话:
The class pair is provided to treat two values as a single unit. It is used in several places within the C++ standard library. In particular, the container classes map and multimap use pairs to manage their elements, which are key/value pairs (See Section 6.6). Another example of the usage of pairs is functions that return two values.
Pair的定义
The structure pair is defined in <utility> as follows:
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&);}namespace std { //comparisons template <class T1, class T2> bool operator== (const pair<T1,T2>& x, const pair<T1,T2>& y) { return x.first == y.first && x.second == y.second; } //similar: !=, <=, >, >= 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); } //create value pair only by providing the values template <class T1, class T2> pair<Tl,T2> make_pair (const T1& x, const T2& y) { return pair<T1,T2>(x, y); }}
Pair的使用
std::pair<int,float> p; //initialize p. first and p.second with zerovoid f(std::pair<int,const char*>);void g(std::pair<const int.std::string>);void foo { std::pair<int,const char*> p(42,"hello"); f(p); //OK: calls built-in default copy constructor g(p); //OK: calls template constructor}std::make_pair(42, ‘@‘); //or std::pair<int,char>(42,‘@‘);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}std::pair<int,float>(42,7.77);//does not yield the same asstd::make_pair(42,7.77);
The C++ standard library uses pairs a lot.
For example, the map and multimap containers use pair as a type to manage their elements, which are key/value pairs. See Section 6.6, for a general description of maps and multimaps, and in particular page 91 for an example that shows the usage of type pair. Objects of type pair are also used inside the C++ standard library in functions that return two values (see page 183 for an example).
STL之Pairs