CodeBlanks Logo Icon CodeBlanks

std::vector

Learn to use dynamic arrays with std::vector.

std::vector

std::vector is a dynamic array that grows automatically. You add elements to the end with push_back; size() returns the count. Memory is contiguous, so it is cache-friendly.

Example: std::vector<int> v; v.push_back(10); v.push_back(20);. Now v.size() returns 2. v[0] accesses the first element, which is 10. vector is the most commonly used STL container; random access is O(1).

Vector access

You access vector elements with [] or .at(). v[0] is the first element, v[1] the second. .at(0) does bounds checking; it throws on out-of-range access.

Example: v[0] is fast but undefined for out-of-bounds indices. v.at(0) is safer but slightly slower. Looping: for (int i = 0; i < v.size(); ++i) std::cout << v[i];. This prints all elements in order.

Practice Work with vector

Create std::vector<int> v;. Add 10, 20, 30 with push_back. Print v.size() and v[0] on separate lines with std::cout.

Starter code

main.cpp
#include <iostream>
#include <vector>

// create a vector and add three elements

int main() {
    // print size and first element
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    std::cout << v.size() << std::endl;
    std::cout << v[0] << std::endl;
    return 0;
}

Expected output

3
10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does push_back do?

main.cpp
v.push_back(10);
  • Removes the first element
  • Clears all elements
  • Adds an element to the end Correct answer
  • Fixes the size

Explanation: push_back appends a new element to the vector.

2 Complete the push_back call

Question
v.push_back(____);
Answer
v.push_back(10);

Explanation: v.push_back(10); adds 10 to the vector.

3 Match method to role

Term Meaning
push_back Add to end
size() Element count
v[0] First element
pop_back Remove last

All lessons in Intermediate