Using STL With Pointers to Objects


Although STL containers are commonly used to store entire objects, it is sometimes necessary to organize and manipulate pointers to objects. Unfortunately, the standard STL algorithm set is not designed for pointer manipulation, and it is often difficult to perform simple tasks such as searching and sorting collections of pointers to objects.

Rather than create a proprietary collection interface to solve this problem, Recursion Software has created two function adapters. Using these function adapters, the existing standard algorithms can manipulate collections of pointers to objects as if they are collections of objects. This approach is in harmony with the spirit of the Standard Template Library. The os_deref1 function object enables unary function adapters to work with pointers to objects; os_deref2 adapts binary function adapters.

In the following example, a vector of pointers to integers is created and then sorted. Since the sort algorithm requires a binary function object to perform object comparisons, os_deref2 is used to adapt less<int> for int* comparisons.

Example <ospace/helper/examples/deref3.cpp>
#include <ospace/std/iostream>
#include <ospace/std/vector>
#include <ospace/helper.h>

template< class T >
class print : public os_unary_function< T, T >
  {
  public:
    T operator()( const T& t ) const
      {
      cout << t << ' ';
      return t;
      }
  };

void
main()
  {
  vector< int* > d;
  d.push_back( new int( 42 ) );
  d.push_back( new int( 03 ) );
  d.push_back( new int( 86 ) );
  d.push_back( new int( 69 ) );
  d.push_back( new int( 21 ) );

  cout << "Unsorted:\n\t";
  os_for_each( d, os_deref1( print< int >() ) );
  cout << endl;

  os_sort( d, os_deref2( less< int >() ) );

  cout << "Sorted:\n\t";
  os_for_each( d, os_deref1( print< int >() ) );
  cout << endl;
  }

Unsorted:
        42 3 86 69 21
Sorted:
        3 21 42 69 86

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