#include <iostream> #include <vector> using namespace std; /* * Simple STL linked list demo. */ int 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 can shrink and grow, and you can ask it how bit it is. It still won't check your subscripts for you, though.