C++ Vectors

// vectors.cpp
//
// compile: g++ -Wall -o vectors vectors.cpp

#include <vector>
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
  vector<unsigned char> a;    // create an empty vector of unsigned 8-bit integers
  vector<float> b( 5, 0.0 );  // create a vector of 5 floats, each initalized to a value of 0.0

  a.push_back( 4 );           // add the value '4' to the end of vector 'a'
  a.push_back( 1 );           // add another value to the end of vector 'a'

  b[0] = 2.0;                 // change value of first element in 'b' ... no error checking on index value

  for ( unsigned int i=0; i<b.size(); i++ ) {
    b.at( i ) = 4.0;           // change all values in 'b' to 4.0
    // b[i] = 4.0;             // also works but does not throw an error if 'i' is out of range
  }

  // Access vector contents using indexing
  cout << "a contains:";
  for ( unsigned int i=0; i<a.size(); i++ )
    cout << " " << (int) a[i];
  cout << endl;

  // Access vector contents using an "iterator"
  cout << "a contains:";
  vector<unsigned char>::iterator it;
  for ( it=a.begin(); it<a.end(); it++ )
    cout << " " << (int) *it;
  cout << endl;

  // Remove all elements in 'a'
  a.clear();

  // Populate vector with values
  for ( unsigned int i=0; i<8; i++ )
    a.push_back( i );

  std::cout << "new a contains:";
  for ( unsigned int i=0; i<a.size(); i++ )
    std::cout << " " << (int) a[i];
  std::cout << std::endl;

  // Randomly remove a few items from 'a'
  srandomdev(); // 'seed' the random number generator
  for ( unsigned int i=0; i<2; i++ ) {
    int nElements = a.size();
    int idx = random() % nElements;
    a.erase( a.begin()+idx );
  }

  std::cout << "a now contains:";
  for ( unsigned int i=0; i<a.size(); i++ )
    std::cout << " " << (int) a[i];
  std::cout << std::endl;

  return 0;
}

vectors.cpp



McGill ©2003-2020 McGill University. All Rights Reserved.
Maintained by Gary P. Scavone.