CS 112
Introduction to Data Structures
Week 05
Generic Containers
Eric Araújo
Calvin University · Fall 2026
typedefvector
typedef double Item; // in Vec.h
Vec scores; // holds doubles ✓
Vec names; // also doubles ✗
typedef and every Vec in the program changes with it.
Want a Vec of doubles and a Vec of strings in one program? You'd need two copies
of the class with different names.
template <typename Item>
class Vec {
public:
void append(const Item &it);
private:
Item *myArray;
unsigned mySize;
};
Vec<double> scores; // a Vec of doubles
Vec<string> names; // a Vec of strings
Vec<double> and Vec<string> are two different, separately compiled classes.typedef double Item;: get it workingtemplate <typename Item> above the class.cpp, put that same line above every methodVec:: to Vec<Item>::#include it
template <typename Item>
void Vec<Item>::append(const Item &it) { ... }
Vec<string> doesn't exist until someone writes it. The compiler generates the class on demand, which means the full body must be visible wherever it's used: so it lives in the header.
vector
#include <vector>
vector<int> scores;
scores.push_back(90); // append
scores.push_back(85);
cout << scores.size(); // 2
cout << scores[0]; // 90
vector, list, stack, queue, set, map. You've just built a simplified vector: from here on you may use the real one.
vector<string>::iterator it;
for (it = names.begin(); it != names.end(); ++it) {
cout << *it << endl; // dereference, like a pointer
}
for (const string &name : names) { // the modern way
cout << name << endl;
}
begin(): points at the first elementend(): points just past the last one*it to read, ++it to advance.
v[i] → *(myArray + i * sizeof(Item))
myArray[mySize] = it;
++mySize;
2 operations → constant
allocate 2n
copy n items
delete old
≈ 3n + 5 → linear
Start empty and append 16 items, doubling each time we fill up:
| Append # | Capacity before | Copies |
|---|---|---|
| 1 | 0 | 0 |
| 2 | 1 | 1 |
| 3 | 2 | 2 |
| 5 | 4 | 4 |
| 9 | 8 | 8 |
| the other 11 | none | 0 |
append() on a dynamic array?
One template, many types.
(the template compiles fine. Item does not.)
| Operation | Dynamic array | Why |
|---|---|---|
v[i] | constant | address arithmetic |
append() | amortized constant | doubling spreads the copy |
insert() at front | linear | everything shifts |
remove() from middle | linear | everything after shifts |
| copy constructor | linear | copies every element |
getSize() | constant | we stored the count |
Vec<int> and Vec<string> are two separately generated classesbegin() and end()
This deck stands on earlier CS112 materials by
Joel Adams and Victor Norman · adapted and extended by Eric Araújo