C++ Standard Template Library (STL) vector class example

This C++ program illustrates how to use the Standard Template Library (STL) vector class


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

int main()
{
    // vector is a template, the <int> means it is a vector of ints
    vector<int> numbers;  

    // push_back() puts a new value at the end (or back) of the vector
    for (int i = 0; i < 10; i++)
        numbers.push_back(i);

    cout << "print all elements in vector" << endl;

    // This is one way to iterate through a vector and print all the values
    for (int i = 0; i < numbers.size(); i++)
        cout << numbers[i] << endl;

    // This is the preferred way to iterate through a vector

    // an iterator is a special object used to keep track of internal structures
    vector<int>::iterator iter;
    for (iter = numbers.begin(); iter != numbers.end(); iter++)
        cout << *iter << endl;

    cout << "now print it backwards" << endl;
    iter = numbers.end();
    for (iter--; iter != numbers.begin(); iter--)
        cout << *iter << endl;
    cout << *iter << endl;
}

// In order to motivate why the iterator mechanism show above is more
// efficient that using the index method (the numbers[i] method)
// consider how you would implement finding a specific element of a
// linked list.  Each time this function is called it has to start
// at the head of the list.

/*
bool List::index(int i, int &value)
{
    Node *ptr;
    for (ptr = m_head; i > 0; ptr = ptr->m_next, i--)
        ;
    if (ptr != NULL)
    {
        value = ptr->m_value;
        return true;
    }
    else return false;
}
*/

Bookmark and Share
Tags:

Leave a Reply


You must be logged in to comment.