Name
make_pair function template — Constructs a pair object
Synopsis
template <typename T1, typename T2>
pair<T1,T2> make_pair(T1 a, T2 b);
Constructs a pair<T1,T2>
object and initializes
it with the values a
and b
. The advantage of using make_pair
over a simple pair<>
constructor is that the
compiler can deduce the types T1
and T2
from the values a
and b
. Example 13-39 shows a typical
use of make_pair
.
Example
std::map<std::string, int> wordcounts;
wordcounts.insert(std::make_pair("hello", 1));
// Functor, suitable for passing to for_each to find minimum and maximum values
// in a range
template<typename T>
class minmax
{
public:
minmax( ) : min_(std::numeric_limits<T>::max( )),
max_(std::numeric_limits<T>::min( ))
{}
void operator( )(const T& x) {
if (x < min_) min_ = x;
if (max_ < x) max_ = x;
}
operator std::pair<T,T>( ) const {
returnstd::make_pair(min_, max_);
}
private:
T min_;
T max_;
};
int main( )
{
std::vector<int> v;
// Fill v with data.
std::pair<int,int> mm =
std::for_each(v.begin( ), v.end( ), minmax<int>( ));
// Do something with mm.
}
See Also
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.