Step 1 of 6
std::vector basics
std::vector<T> is the most used type in C++. It's a dynamic array: elements stored side by side like a C array, but it grows as needed, knows its own size, and frees its memory automatically. It's everything you built by hand with malloc, realloc and a capacity counter, done correctly.
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> queue = {"ada", "linus"};
queue.push_back("grace");
std::cout << queue.size() << " waiting, first " << queue.front() << ", last " << queue.back() << "\n";
queue[1] = "ken";
queue.pop_back();
for (const std::string& name : queue) std::cout << name << " ";
std::cout << "\n";
std::vector<int> zeros(5);
std::vector<int> sevens(3, 7);
std::cout << zeros.size() << " " << sevens[2] << " " << queue.empty() << "\n";
}
3 waiting, first ada, last grace
ada ken
5 7 0
The essentials
std::vector<T>holds elements of typeT:std::vector<int>,std::vector<std::string>. The<T>is a template argument (templates get their own module).push_back(x)appends;pop_back()removes the last element.size(),empty(),front(),back().v[i]indexes without checking, like a C array.v.at(i)checks, and reports an out-of-range error instead of reading garbage (in standard C++ it throws an exception, which ends the program unless something catches it).std::vector<int> zeros(5)makes 5 zero-initialized elements;(3, 7)makes three 7s. Braces{3, 7}would instead mean "the two elements 3 and 7".
Internally, a vector keeps a heap buffer with a capacity and grows it by a constant factor (GCC's library doubles it) when full, exactly like your realloc exercise. The Watch it run link shows the buffer moving to a bigger heap block as it grows.
Your turn: fill in the blanks.