LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 4 of 27

Arrays and Vectors

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Arrays and Vectors · Study material

Arrays and vectors in C++ store many values of the same type in one contiguous block of memory, so any element can be reached instantly by its index. C++ offers three choices: the built-in C-style array inherited from C, the fixed-size std::array, and the resizable std::vector – the container professionals use by default. Knowing when an array decays to a pointer, what size() and capacity() mean, how to erase elements safely and why at() is safer than [] is essential for coding interviews and competitive programming. This page explains all of it with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.

On this page

  • C-style arrays: declaration, initialization, std::size, decay to pointers
  • Passing arrays to functions and 2D arrays
  • std::array: a fixed-size array that behaves like a value
  • std::vector: adding, removing, resizing, size vs capacity, 2D vectors
  • Bounds checking, iterator invalidation, algorithms and std::span

C-style arrays

An array declaration gives the element type, the name and a size that must be a compile-time constant: int marks[5];. Indexes run from 0 to size − 1. A brace initializer may be shorter than the array – the rest is zero – and the size can be omitted when an initializer is given. A local array without an initializer contains garbage; {} zeroes it. std::size(arr) (C++17) gives the number of elements.

#include <iostream>
#include <iterator>   // std::size

int main() {
    int marks[5] = {78, 92, 65};           // remaining elements become 0
    double prices[] = {9.5, 12.0, 4.25};   // size deduced: 3
    int zeros[4]{};                        // all zero
    marks[3] = 88;                         // index from 0 to size-1

    std::cout << std::size(marks) << ' ' << std::size(prices) << ' ' << sizeof(marks) << '\n';
    for (int m : marks) std::cout << m << ' ';           // range-based for
    std::cout << '\n' << zeros[3] << ' ' << prices[2] << '\n';
    return 0;
}

Output

5 3 20
78 92 65 88 0
0 4.25

Arrays decay to pointers

In most expressions an array name converts to a pointer to its first element. That is why arr[i] equals *(arr + i), why arrays cannot be assigned or returned, and why an array parameter is really a pointer: inside the function sizeof gives the pointer size and the length is lost. Pass the size separately, take the array by reference, or – better – use std::array, std::vector or std::span.

#include <iostream>

// An array parameter is really a pointer: the size is lost, so pass it separately
int sum(const int arr[], std::size_t n) {
    int total = 0;
    for (std::size_t i = 0; i < n; ++i) total += arr[i];
    std::cout << "sizeof inside: " << sizeof(arr) << '\n';     // size of a pointer
    return total;
}

// A reference to an array keeps the size as part of the type
template <std::size_t N>
int sum_ref(const int (&arr)[N]) {
    int total = 0;
    for (int x : arr) total += x;
    return total + static_cast<int>(N) * 0;
}

int main() {
    int data[6] = {1, 2, 3, 4, 5, 6};
    std::cout << "sizeof outside: " << sizeof(data) << '\n';
    std::cout << sum(data, 6) << ' ' << sum_ref(data) << '\n';
    int* p = data;                           // the name decays to a pointer to the first element
    std::cout << *p << ' ' << *(p + 2) << ' ' << p[5] << '\n';
    return 0;
}

Output

sizeof outside: 24
sizeof inside: 8
21 21
1 3 6

Two-dimensional arrays

int m[3][4] is an array of 3 rows, each an array of 4 ints, stored row by row (row-major order): element [r][c] is at position r × cols + c. Nested loops visit rows and columns.

#include <iostream>

int main() {
    int m[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
    };
    int row_sum[3]{}, col_sum[4]{};
    for (int r = 0; r < 3; ++r)
        for (int c = 0; c < 4; ++c) {
            row_sum[r] += m[r][c];
            col_sum[c] += m[r][c];
        }
    for (int s : row_sum) std::cout << s << ' ';
    std::cout << "| ";
    for (int s : col_sum) std::cout << s << ' ';
    std::cout << "\nelement [1][2] = " << m[1][2] << ", stored as element " << 1 * 4 + 2 << " of 12\n";
    return 0;
}

Output

10 26 42 | 15 18 21 24
element [1][2] = 7, stored as element 6 of 12

std::array – a safer fixed-size array

std::array<T, N> (in <array>) wraps a C array with no overhead but behaves like a normal value: it knows its size(), can be copied, assigned, compared and returned from functions, and offers at() with bounds checking.

#include <array>
#include <iostream>
#include <stdexcept>

int main() {
    std::array<int, 4> a{10, 20, 30, 40};           // fixed size, knows its size, can be copied
    std::array<int, 4> b = a;                       // copy (impossible with C arrays)
    b[0] = 99;
    std::cout << a.size() << ' ' << a.front() << ' ' << a.back() << ' ' << b[0] << '\n';
    std::cout << (a == b) << ' ' << (a < b) << '\n';   // element-wise comparison
    try {
        std::cout << a.at(4) << '\n';                // at() checks the index
    } catch (const std::out_of_range&) {
        std::cout << "index 4 is out of range\n";
    }
    return 0;
}

Output

4 10 40 99
0 1
index 4 is out of range

std::vector – the dynamic array

std::vector<T> (in <vector>) manages a heap buffer that grows automatically. Elements are still contiguous, so indexing is O(1) and it works with every algorithm. Adding or removing at the end is fast (amortized O(1)); inserting or erasing in the middle shifts the following elements (O(n)).

OperationMeaningCost
v.push_back(x) / v.emplace_back(args…)append (copy/move) / construct in placeamortized O(1)
v.pop_back()remove the last elementO(1)
v[i] / v.at(i)access (unchecked / checked)O(1)
v.front() / v.back()first / last elementO(1)
v.insert(it, x) / v.erase(it)insert / remove at a positionO(n)
v.size() / v.empty()number of elements / is it emptyO(1)
v.capacity() / v.reserve(n)allocated room / ensure room for n–
v.resize(n) / v.clear()change the size / remove allO(n)
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<int> v;                    // empty, grows as needed
    for (int i = 1; i <= 5; ++i)
        v.push_back(i * i);                // add at the end
    std::cout << v.size() << ' ' << v.front() << ' ' << v.back() << ' ' << v[2] << '\n';

    v.pop_back();                          // remove the last element
    v.insert(v.begin(), 0);                // insert at the front
    v.erase(v.begin() + 2);                // erase the element at index 2
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';

    std::vector<std::string> names{"Asha", "Ravi"};
    names.emplace_back(3, 'z');            // constructs std::string(3, 'z') in place
    std::cout << names.size() << ' ' << names.back() << ' ' << names.empty() << '\n';
    return 0;
}

Output

5 1 25 9
0 1 9 16
3 zzz 0

Constructing and resizing vectors

Parentheses and braces mean different things: std::vector<int> v(4, 7) is four 7s, while v{4, 7} is the two elements 4 and 7. size is the number of elements; capacity is how many fit before a reallocation. reserve changes only the capacity, resize changes the size.

#include <iostream>
#include <vector>

void print(const std::vector<int>& v) {
    std::cout << '[';
    for (std::size_t i = 0; i < v.size(); ++i) std::cout << (i ? " " : "") << v[i];
    std::cout << "] size " << v.size() << '\n';
}

int main() {
    std::vector<int> a(4);          // 4 zeros
    std::vector<int> b(4, 7);       // 4 sevens
    std::vector<int> c{4, 7};       // two elements: 4 and 7
    print(a); print(b); print(c);

    b.resize(6);                    // grows, new elements are 0
    print(b);
    b.resize(2);                    // shrinks
    print(b);

    std::vector<int> d;
    d.reserve(100);                 // capacity for 100, size still 0
    std::cout << d.size() << ' ' << (d.capacity() >= 100) << '\n';
    return 0;
}

Output

[0 0 0 0] size 4
[7 7 7 7] size 4
[4 7] size 2
[7 7 7 7 0 0] size 6
[7 7] size 2
0 1

Erasing elements and using algorithms

To remove every element with a certain value, C++20 offers std::erase(v, value) and std::erase_if(v, pred). Before C++20 the erase-remove idiom was used: v.erase(std::remove(v.begin(), v.end(), x), v.end());. Algorithms in <algorithm> and <numeric> – sort, find, count, accumulate, max_element, reverse – work on any range given by two iterators.

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> v{5, 3, 8, 3, 9, 1, 3, 6};
    auto removed = std::erase(v, 3);                       // C++20: remove every 3
    std::erase_if(v, [](int x) { return x > 8; });         // remove by condition
    std::cout << removed << " removed: ";
    for (int x : v) std::cout << x << ' ';

    std::sort(v.begin(), v.end());
    int total = std::accumulate(v.begin(), v.end(), 0);
    auto it = std::find(v.begin(), v.end(), 6);
    std::cout << "\nsorted: ";
    for (int x : v) std::cout << x << ' ';
    std::cout << "| sum " << total << " | 6 at index " << (it - v.begin())
              << " | max " << *std::max_element(v.begin(), v.end()) << '\n';
    return 0;
}

Output

3 removed: 5 8 1 6
sorted: 1 5 6 8 | sum 20 | 6 at index 2 | max 8

2D vectors and jagged rows

A std::vector<std::vector<int>> builds a grid whose size is known only at run time, and each row may have a different length. (For large numeric grids a single vector indexed as r * cols + c is faster, because it is one contiguous block.)

#include <iostream>
#include <vector>

int main() {
    int rows = 3, cols = 4;                                    // sizes known only at run time
    std::vector<std::vector<int>> grid(rows, std::vector<int>(cols, 0));
    for (int r = 0; r < rows; ++r)
        for (int c = 0; c < cols; ++c)
            grid[r][c] = r * cols + c;

    std::vector<std::vector<int>> triangle;                    // rows of different lengths
    for (int r = 1; r <= 4; ++r) triangle.push_back(std::vector<int>(r, r));

    std::cout << grid.size() << 'x' << grid[0].size() << ", last = " << grid[2][3] << '\n';
    for (const auto& row : triangle) {
        for (int x : row) std::cout << x;
        std::cout << ' ';
    }
    std::cout << '\n';
    return 0;
}

Output

3x4, last = 11
1 22 333 4444

Bounds checking and iterator invalidation

v[i] with an invalid index is undefined behaviour – it may print garbage or crash much later. v.at(i) checks and throws std::out_of_range. When a vector grows past its capacity it moves its elements to a new buffer, so all pointers, references and iterators to its elements become invalid; insert and erase invalidate those at and after the position. Never keep an iterator across a push_back unless enough capacity was reserved.

std::span – a view of contiguous data

C++20 std::span<T> (in <span>) is a non-owning pointer + length. A function taking std::span<const int> accepts C arrays, std::array and std::vector without copying and without losing the size; subspan, first and last give views of parts.

#include <array>
#include <iostream>
#include <span>
#include <vector>

// One function for C arrays, std::array and std::vector – no copy, size included
double average(std::span<const int> values) {
    if (values.empty()) return 0;
    long long sum = 0;
    for (int v : values) sum += v;
    return static_cast<double>(sum) / values.size();
}

int main() {
    int c_arr[] = {1, 2, 3, 4};
    std::array<int, 3> std_arr{10, 20, 30};
    std::vector<int> vec{5, 5, 5, 5, 6};
    std::cout << average(c_arr) << ' ' << average(std_arr) << ' ' << average(vec) << '\n';
    std::cout << average(std::span(vec).subspan(1, 3)) << ' ' << average(std::span(vec).last(2)) << '\n';
    return 0;
}

Output

2.5 20 5.2
5 5.5

Which one should I use?

C arraystd::arraystd::vector
Sizefixed, compile timefixed, compile timegrows at run time
Knows its sizeno (decays)yesyes
Copy / assign / returnnoyesyes
Memorystack (local)stack (local)heap buffer
Bounds-checked accessnoat()at()
Use forC APIs, legacy codesmall fixed setsalmost everything else

Common mistakes

  • Off-by-one: for (int i = 0; i <= n; ++i) reads one element past the end.
  • sizeof on an array parameter gives the pointer size, not the array size.
  • Confusing () and {}: vector<int>(5) is five zeros, vector<int>{5} is one element.
  • Erasing inside a range-for loop invalidates the iterator – use std::erase_if.
  • Keeping references across push_back – they may dangle after a reallocation.
  • Comparing signed and unsigned in i < v.size() – use std::size_t or range-for.
  • Passing vectors by value to read-only functions – use const std::vector<T>&.

Key points to remember

  • Indexes start at 0; the last element is size − 1.
  • C arrays decay to pointers and lose their size when passed to functions.
  • std::array is fixed and copyable; std::vector grows and is the default choice.
  • size = elements, capacity = room; reserve affects capacity, resize affects size.
  • at() checks bounds; [] does not.
  • Growth invalidates pointers and iterators into a vector.

Frequently asked questions

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

A C array has a fixed size known at compile time and decays to a pointer; a vector can grow and shrink at run time, knows its size, can be copied and returned, and frees its memory automatically.

Is std::vector slower than an array?

Element access is just as fast – both are contiguous. The only extra cost is the heap allocation, which reserve keeps to one.

How do I get the length of an array?

Use std::size(arr) for C arrays, and .size() for std::array and std::vector. Inside a function that received a C array as a parameter the length is no longer available.

Where can I learn more?

Read C++ std::vector and std::array, deque and list, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links