Handout 20c

A STL Example*


Version 1: Standard C++

Here is a standard C++ program to read a list of integers, sort them and print them:

#include <stdlib.h>
#include <iostream.h>
 
// a and b point to integers.  cmp returns -1 if a is less than b, 
// 0 if they are equal, and 1 if a is greater than b.
inline int cmp (const void *a, const void *b)
{
  int aa = *(int *)a;
  int bb = *(int *)b;
  return (aa < bb) ? -1 : (aa > bb) ? 1 : 0;
}
 
// Read a list of integers from stdin
// Sort (c library qsort)
// Print the list
 
main (int argc, char *argv[])
{
  const int size = 1000;  // array of 1000 integers
  int array [size];
  int n = 0;
  // read an integer into the n+1 th element of array
  while (cin >> array[n++]);
  n--; // it got incremented once too many times 
 
  qsort (array, n, sizeof(int), cmp);
 
  for (int i = 0; i < n; i++)
    cout << array[i] << "\n";
}

Version 2: containers, iterators, algorithms

#include <string.h>
#include <algo.h>
#include <vector.h>
#include <stdlib.h>
#include <iostream.h>
 
main ()
{
  vector<int> v;  // create an empty vector of integers
  int input;
  while (cin >> input)    // while not end of file
    v.push_back (input);  // append to vector
 
  // sort takes two random iterators, and sorts the elements between
  // them.  As is always the case in STL, this includes the value
  // referred to by first but not the one referred to by last; indeed,
  // this is often the past-the-end value, and is therefore not
  // dereferenceable.
  sort(v.begin(), v.end());
 
  int n = v.size();
  for (int i = 0; i < n; i++)
    cout << v[i] << "\n";
}

Example using containers

Here is a program that generates a random permutation of the first n integers, where n is specified on the command line.

include <iostream.h>
#include <vector.h>
#include <algo.h>
#include <iterator.h>
 
main (int argc, char *argv[])
{
  int n = atoi (argv[1]); // argument checking removed for clarity
 
  vector<int> v;
  for (int i = 0; i < n; i++)            // append integers 0 to n-1 to v
    v.push_back (i);
 
  random_shuffle (v.begin(), v.end());                         // shuffle
  copy (v.begin(), v.end(), ostream_iterator<int> (cout, "\n")); // print
}

This program creates an empty vector and fills it with the integers from 0 to n. It then shuffles the vector and prints it out.


*from http://www.cs.brown.edu/people/jak/proglang/cpp/stltut/tut.html