C++ Arrays and Vectors

C++ arrays and vectors store multiple values of the same type. Modern C++ prefers std::array for fixed sizes and std::vector for collections that grow, rather than raw C-style arrays.

C-Style Arrays

Built-in arrays work like in C. They have a fixed size and do not know their own length when passed to functions.

#include <iostream>

int main() {
    int marks[3] = {70, 85, 90};
    for (int m : marks) std::cout << m << ' ';
    std::cout << '\n';
}
70 85 90 

std::array

std::array has a fixed size but knows its length and works with standard algorithms.

#include <array>
#include <iostream>

int main() {
    std::array<int, 4> days{31, 28, 31, 30};
    std::cout << "Size: " << days.size() << '\n';
    std::cout << "Last: " << days.back() << '\n';
}
Size: 4
Last: 30

std::vector: The Dynamic Array

std::vector grows automatically as you add elements. It is the default container to reach for in C++.

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> tasks;
    tasks.push_back("Write code");
    tasks.push_back("Test");
    tasks.emplace_back("Deploy");
    tasks.erase(tasks.begin() + 1);   // remove "Test"

    for (std::size_t i = 0; i < tasks.size(); ++i)
        std::cout << i + 1 << ". " << tasks[i] << '\n';
}
1. Write code
2. Deploy

Common Vector Operations

  • push_back / emplace_back: add to the end
  • pop_back: remove the last element
  • size, empty: count and check
  • front, back: first and last element
  • clear: remove everything
  • at(i): bounds-checked access

2D Vectors

#include <iostream>
#include <vector>

int main() {
    std::vector<std::vector<int>> grid(2, std::vector<int>(3, 0));
    grid[1][2] = 5;
    for (const auto& row : grid) {
        for (int v : row) std::cout << v << ' ';
        std::cout << '\n';
    }
}
0 0 0
0 0 5 

Frequently asked questions

What is the difference between vector and array in C++?

std::array has a size fixed at compile time and lives on the stack. std::vector can grow and shrink at runtime and stores its elements on the heap.

What is the difference between push_back and emplace_back?

push_back adds an existing object (copying or moving it), while emplace_back constructs the object in place from arguments. For simple values the difference is negligible.

How do I get the size of a vector in C++?

Call vec.size(). It returns the number of elements as a std::size_t.