C/C++ Arena

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

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.

Next: Loop over a vector