STL Vector
2003-05-28 14:16:06
Category: cpp:stl
Description: Basic example on inserting, finding, and retrieving elements of a stl vector.
Author: detour
Viewed: 10432
Rating: (31 votes)


/* vector.cpp by detour@metalshell.com
 *
 * Basic example on inserting, finding, and retrieving
 * elements of a stl vector.
 *
 * http://www.metalshell.com/
 *
 */
 
#include <iostream>
#include <vector>
#include <string>
 
using namespace std;
 
int main() {
  // Create the vector of type string
  vector<string> myvect;
 
  myvect.push_back("Golden");
  myvect.push_back("Age");
  myvect.push_back("Illuminati");
 
  cout << "Print using iterator.\n";
 
  // Print out all values using an iterator
  vector<string>::iterator i;
  for(i = myvect.begin(); i < myvect.end(); i++)
    cout << (*i) << endl;;
 
  cout << "\nPrint using index.\n";
 
  // Print out all values using an index
  unsigned int index;
  for(index = 0; index < myvect.size(); index++)
    cout << myvect[index] << endl;
 
  cout << "\nSearch for a value.\n";
 
  // Find a value and print it
  i = find(myvect.begin(), myvect.end(), "Illuminati");
  if(i != myvect.end())
    cout << "Found: " << (*i) << endl;
 
  // erase everything in myvect.
  myvect.clear();
 
  // Nothing will be printed.
  for(i = myvect.begin(); i < myvect.end(); i++)
    cout << (*i) << endl;;
 
  return 0;
}