Pairs
class pair 可以将两个值视为一个单元。对于map和multimap,就是用pairs来管理value/key的成对元素。任何函数需要回传两个值,也需要pair。
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;
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&);
}
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,'@')
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
}
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));
std::map<std::string,float> coll;
...
coll.insert(std::make_pair("otto",22.3));