STL Iterators and Regular C Pointers


The following example illustrates the similarity between STL iterators and regular C pointers.

Example <ospace/osstd/ examples/iter0.cpp>
#include <iostream>
#include <vector>

int array[] = { 1, 42, 3 }; // Regular "C" array.
vector< int > v; // STL vector of integers

void
main()
  {
  // Initialize the STL Vector
  v.push_back( 1 );
  v.push_back( 42 );
  v.push_back( 3 );

  // Use pointer to traverse "C" array.
  int* p1;
  for ( p1 = array; p1 != array + 3; ++p1 )
    cout << "array has " << *p1 << "\n";

  // Use iterator to traverse STL vector.
  int_vector::iterator p2;
  for ( p2 = v.begin(); p2 != v.end(); ++p2 )
    cout << "vector has " << *p2 << "\n";
  }

array has 1
array has 42
array has 3
vector has 1
vector has 42
vector has 3

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