A vector is a resizable sequence container backed by an array in contiguous storage. It avoids choosing a fixed capacity and removes much of the memory-management burden from dynamically sized collections. section 5.10
Use a vector when fixed arrays create practical or maintenance problems:
- Add elements with push_back without assigning specific index values or maintaining flags for unused positions. section 5.10
- Let the container grow when its backing array fills; reserve expected capacity when repeated reallocations could hurt performance. section 5.10
- Prefer vectors when arrays would force meaningless default construction and potentially create objects with invalid or misleading state. section 7.8
- Use a vector of one element type instead of varargs when a variable-length argument list must remain type-safe. section 6.5
Replacing an awkward Person array
A Person array requires every slot to be default-constructed, so an unused slot may still look like a legitimate person. A vector starts empty and receives only meaningful objects: people.push_back(Person("Susan", 21)); people.push_back(Person("Jason", 25));. The same pattern handles a computed count without new[]: create std::vector<Person> others and call others.reserve(count).
Replacing varargs with a typed vector
Instead of sum(int len, int initial, ...), pass the values as const std::vector<T>&. A template then supports vectors of int or double while the element type remains visible to the compiler.
Listing 5.23 Using a vector to replace awkward arrays
struct Person {
std::string name;
int age;
Person(const std::string& n, int a) : name(n), age(a) {}
};
int main() {
std::vector<Person> people;
Person suzy("Susan", 25);
people.push_back(suzy);
Person anna("Annette", 32);
people.push_back(anna);
std::cout << people[people.size()-1].name << '\n';
int count = 5; // assume this is computed
std::vector<Person> others;
others.reserve(count);
return 0;
}
Inspect the complete vector replacement, including push_back for populated Persons and reserve for a computed capacity. section 5.10










