Pairs


STL defines a templatized pair as an object that simply contains two objects. Pairs of objects can therefore be conveniently stored and passed around as parameters. Once constructed, a pair's items can be accessed using the public data members first and second .

Several algorithms use pair objects to return a pair of items. For example, mismatch() returns a pair of iterators that point to the items that mismatched.

Example <ospace/osstd/ examples/pair0.cpp>
#include <iostream>
#include <algorithm>
#include <utility>

int array1[] = { 1, 4, 8, 3, 2 };
int array2[] = { 1, 4, 7, 2, 3 };

void
main()
  {
  pair< int*, int* > p = mismatch( array1, array1 + 5, array2 );
  cout << "mismatch @ " << *( p.first ) << ", " << *( p.second ) << "\n";
  }

mismatch @ 8, 7

Several STL containers use pair objects to return pairs of items. For example, equal_range() causes a multiset (described in Part 2, "Reference Manual") to return a pair of iterators that indicate the first and last locations a value can be positioned without violating the ordering criteria.

Example <ospace/osstd/ examples/pair1.cpp>
#include <iostream>
#include <algorithm>
#include <set>
#include <utility>

int array[] = { 3, 6, 1, 2, 3, 2, 6, 7, 9 };

typedef multiset< int, less< int > > mset;

void
main()
  {
  mset s( array, array + 9 );
  pair< mset::iterator, mset::iterator > p = s.equal_range( 3 );
  cout << "lower bound = " << *( p.first ) << "\n";
  cout << "upper bound = " << *( p.second ) << "\n";
  }

lower bound = 3
upper bound = 6

The make_pair() function creates a pair from two items.

Example <ospace/osstd/ examples/pair2.cpp>
#include <iostream>
#include <utility>

void
main()
  {
  pair< int, int > p = make_pair( 1, 10 );

  cout << "p.first = " << p.first << "\n";
  cout << "p.second = " << p.second << "\n";
  }

p.first = 1
p.second = 10

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.