------------------------------------------------------------------------------
MC logo
STL Vector 101
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[STL Vector 101] [STL Sorting Vectors] [stlist_cpp] [STL Map 1] [STL Map 2] [Word Counter]
stvec0.cpp
#include <iostream>
#include <vector>

using namespace std;

/*
 * Simple STL linked list demo.
 */
main()
{
        // This declares an empty vector of integers.
        vector<int> iv;

        // Now let's fill the vector with some useless numbers.
        for(int i = 1; i <= 15; ++i)
                iv.push_back(3*i - 10);

        // A vector can be subscripted, so let's print it out that way.
        cout << "A:";
        for(int i = 0; i < iv.size(); ++i)
                cout << " " << iv[i];
        cout << endl;

        // You can also scan the array using an iterator.  To wit:
        int tot = 0;
        for(vector<int>::iterator j = iv.begin(); j != iv.end(); ++j)
                tot += *j;
        cout << "B: total is " << tot << endl;

        // You can change data in the middle of a vector (though it may not
        // be particularly efficient).  You need to use an iterator for that.
        for(vector<int>::iterator j = iv.begin(); j != iv.end(); ++j) {
                // Insert 99 after the first positive item.
                if(*j > 0) {
                        iv.insert(j, 99);
                        break;
                }
        }

        // Let's print it again, only backwards this time.
        cout << "C:";
        for(vector<int>::reverse_iterator j = iv.rbegin(); j != iv.rend(); ++j)
                cout << " " << *j;
        cout << endl;

        // And, now, let's print the odd ones.
        cout << "D:";
        vector<int>::iterator j = iv.begin() + 1;
        for(int cnt = iv.size() / 2; cnt--; j += 2)
                cout << " " << *j;
        cout << endl;
}

The vector is often used as a slightly less-strange alternative to using a plain array. It still won't check you subscripts for you, though.