C++ Arrays & Vectors

Fixed arrays and the dynamic std::vector.

✍️ 2 exercises in this lesson

C-style arrays have a fixed size: int a[3] = {1, 2, 3};

In modern C++, prefer std::vector, a dynamic array that grows automatically:

  • push_back(), pop_back(), size(), empty(), clear()
  • v[i] or the bounds-checked v.at(i)
  • front(), back(), insert(), erase()

Key Takeaways: C++ Arrays & Vectors

Mastering C++ Arrays & Vectors helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C++ Arrays & Vectors Code Example

C++
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> cities = {"Lahore", "Karachi"};
    cities.push_back("Quetta");
    cities.insert(cities.begin(), "Islamabad");

    std::cout << "Count: " << cities.size() << "\n";
    std::cout << "First: " << cities.front() << ", last: " << cities.back() << "\n";
    for (const auto& c : cities) std::cout << "- " << c << "\n";
    return 0;
}
Output
Count: 4
First: Islamabad, last: Quetta
- Islamabad
- Lahore
- Karachi
- Quetta
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ Arrays & Vectors Practice Exercises

Check what you learned in “C++ Arrays & Vectors”.

/ 2 solved
Fill in the blank

Add an element to the end of a vector.

cities.("Quetta");
✓ Correct! Not quite. Try again.
Multiple choice

Which vector method checks bounds and throws on a bad index?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services