make pair usuage
The behavior of this function template is the same as if defined as:
|
|
// make_pair example
#include <utility> // std::pair
#include <iostream> // std::cout
int main () {
std::pair <int,int> foo;
std::pair <int,int> bar;
foo = std::make_pair (10,20);
bar = std::make_pair (10.5,'A'); // ok: implicit conversion from pair<double,char>
std::cout << "foo: " << foo.first << ", " << foo.second << '\n';
std::cout << "bar: " << bar.first << ", " << bar.second << '\n';
return 0;
}
std::pair
you need to specify the types of both elements, whereas std::make_pair
will create a pair with the type of the elements that are passed to it, without you needing to tell it. That's what I could gather from various docs anyways.
See this example from http://www.cplusplus.com/reference/std/utility/make_pair/
pair <int,int> one;
pair <int,int> two;
one = make_pair (10,20);
two = make_pair (10.5,'A'); // ok: implicit conversion from pair<double,char>
Aside from the implicit conversion bonus of it, if you didn't use make_pair you'd have to do
one = pair<int,int>(10,20)
every time you assigned to one, which would be annoying over time..
There is no difference between using
make_pair
and explicitly calling the pair
constructor with specified type arguments. std::make_pair
is more convenient when the types are verbose because a template method has type deduction based on its given parameters. For example,std::vector< std::pair< std::vector<int>, std::vector<int> > > vecOfPair;
std::vector<int> emptyV;
// shorter
vecOfPair.push_back(std::make_pair(emptyV, emptyV));
// longer
vecOfPair.push_back(std::pair< std::vector<int>, std::vector<int> >(emptyV, emptyV));
Comments
Post a Comment