Monday, November 7, 2011

make_pair stl

make_pair c++ / Convenience Function make_pair()

The make_pair() template function enables you to create a value pair without writing the types explicitly:

Using make_pair() should cost no runtime. The compiler should always optimize any implied overhead.

namespace std {
   //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);
   }
}

For example, by using make_pair() you can write

std::make_pair(42, '@')

instead of

std::pair<int,char>(42,'@')

In particular, the make_pair() function makes it convenient to pass two values of a pair directly to a function that requires a pair as its argument. Consider the following example:

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
}

As the example shows, make_pair() makes it rather easy to pass two values as one pair argument. It works even when the types do not match exactly because the template constructor provides implicit type conversion. When you program by using maps or multimaps, you often need this ability.

Note that an expression that has the explicit type description has an advantage because the resulting type of the pair is clearly defined. For example, the expression

std::pair<int,float>(42,7.77)

does not yield the same as

std::make_pair(42,7.77)

The latter creates a pair that has double as the type for the second value (unqualified floating literals have type double). The exact type may be important when overloaded functions or
templates are used. These functions or templates might, for example, provide versions for both float and double to improve efficiency.

See Also:

No comments:

Post a Comment