------------------------------------------------------------------------------
MC logo
Vector Iterator Demo
[^] 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]
[Template Functions] [Template Generalized Stack] [Template Generalized Stack Driver] [Array Template Stack] [Array Template Test Driver] [Generalized Safe Array] [Safe Array Demo] [Vector Iterator Demo]
vec2.cc
// There is a standard vector class in C++, but it is based on a
// template, not on polymophism.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

// Generic printing function.
template <typename T>
void print_arr(vector<T> &v)
{
        int m = 0;
        for(typename vector<T>::iterator i = v.begin(); i != v.end(); ++i) {
                if(i != v.begin()) cout << " ";
                cout << *i;
        }
}

main()
{
        vector<string> v;

        v.push_back("How");
        v.push_back("are");
        v.push_back("you");
        v.push_back("today");
        v.insert(v.begin() + 3, "doing");

        print_arr(v);
        cout << endl << v.front() << " " << v.back() << endl;

        vector<int> q;
        q.push_back(45);
        q.push_back(3);
        q.push_back(-34);
        q.push_back(75);
        q.push_back(9);
        vector<int>::iterator qi = q.end() - 3;
        q.insert(qi, 44);
        qi = q.begin() + 4;
        *qi = 111;

        print_arr(q);
        cout << endl;
}

Here we've made a template function which can receive a vector of anything. (Well, effectively anything that can be printed.)