Vector Printing Function
// 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. Note: This function can print a vector // of any type which iostream can print. If you send it a vector of some // other type, you're out of luck. 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; } } int 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; }

This example shows a template function to print a vector of whatever content type. This is a common pattern, where a template type paramter becomes the conent type of a library container.

It's also worth noting that the type T itself is never used alone; always the type of vector.