4.2. The standard template library


The STL without the objects

You can use STL functions that require iterators with normal C arrays, not just STL objects. The end of an array arr with N elements can be expressed as arr + N. Thus

sort(arr, arr + N);

will sort an array of N objects.

The STL also has several places where it requires function objects. Depending on the nature of the object required, one can use ordinary functions instead. So for example, to sort an array of pointers to ints by the values pointed to, one could do the following:

bool compare(char * const &a, char * const &b)
{ return *a < *b; }
.
.
.
sort(arr, arr + N, compare);

HP/SGI/GCC extensions to the STL

The STL manual lists several extensions to the STL which are not part of the C++ standard. GCC 3 implements these extensions, but getting access to them is not entirely obvious. The first thing to do is to prepend ext/ to include filenames e.g. #include <ext/hash_set>. You also need to include the __gnu_cxx namespace e.g. using namespace __gnu_cxx.

A useful extension for loading data into arrays is the copy_n extension function. Here is an example:

#include <ext/algorithm>
#include <iterator>
#include <fstream>

using namespace std;
using namespace __gnu_cxx;

int main()
{
    int N;
    int numbers[100];

    ifstream in("file.in");
    in >> N;
    copy_n(istream_iterator<int>(in), N, numbers);
}

[Prev] [Next] [Up]

Last updated Sun Nov 28 22:04:38.0000000000 2004. Copyright Bruce Merry (bmerry '@' gmail dot. com).