http://www.alper.net/ Eyup Alper Yoney

2Jan/100

C++, Functions That Return Two Values

I am going to explain the class pair that is provided to treat two values as one. The class pair is used several times in STL. The container classes map and multimap use the class pair to handle the key/value pairs. The other usage of the pair class is functions that return two values. I choose the title as 'Functions That Return Two Value' instead of 'The class pair' because it sounds much more attractive since developers used to hear functions can return one value.

The pair structure is defined in <utility> as follows;

namespace std {
  template<class T1, class T2>
  struct pair {
    typedef T1 first_type;
    typedef T2 second_type;

    T1 fist;
    T2 second;

    pair() : first(T1()), second(T2()) {}
    pair(const T1& val1, const T2& val2) : first(val1), second(val2) {}
    template<class Other1, class Other2>
    pair(const pair<Other1, Other2>& p) : first(p.first), second(p.second) {}
  };
}
 

The pair is defined as struct. Therefore, accessing the members (first and second) is possible. The definition is short and straightforward. However, the template version of the copy constructor may seen confusing. The template copy constructor is called whenever implicit conversion is needed. There are many good books about C++, STL and Templates, two of them are as follows;

1. C++ Primer, by Stanley B. Lippman, Josée LaJoie, Barbara E. Moo
2. The C++ Standard Library: A Tutorial and Reference, by Nicolai M. Josuttis

The make_pair() template function makes the life easier by creating the pair without explicit types.

namespace std {
  template<class T1, class T2>
  make_pair(const T1& val1, const T2& val2)
  {
    return pair<T1, T2>(val1, val2);
  }
}
 

In conclusion, here is an example of function that returns two values, including use of the pair class and make_pair function.

#include <cstdlib>
#include <iostream>
#include <utility>

using namespace std;

const double PI = 3.14;

pair<double, double> areaAndCircumferenceOfCircle(double r)
{
  return make_pair((PI * r * r), (2 * PI * r));
}

int main(int argc, char *argv[])
{
  pair<double, double> circle;
 
  circle = areaAndCircumferenceOfCircle(5);
  cout << "Area: " << circle.first << endl;
  cout << "Circumference: " << circle.second << endl;
 
  return 0;
}
 

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


Trackbacks are disabled.