Dynamic Arrays and Linked Lists

ArrayList in C++: Using std::vector

C++ has no ArrayList class. std::vector does the same job: a list that grows as you add elements. Here is how to create, read, loop over and resize one.

On this page
  1. What is an ArrayList in C++?
  2. Creating a vector
  3. Adding, reading and removing elements
  4. Looping through the elements
  5. Size and capacity
  6. Passing a vector to a function
  7. How this compares with C arrays
  8. Common mistakes
  9. When to use something else

What is an ArrayList in C++?

If you searched for an arraylist in C, you probably want a list that can grow as you add items. ArrayList is a class name from Java. C++ has no class with that name, but the standard library’s std::vector does the same job. It stores values in order, keeps them in one block of memory, and grows automatically when you add more. It lives in the <vector> header.

C has no growable array at all. In C, you manage that memory yourself with malloc and realloc. C++ wraps that work inside std::vector, so you can focus on the data.

Creating a vector

A vector holds one element type, written in angle brackets. These lines show a few common ways to create one:

#include <vector>

std::vector<int> empty;               // no elements yet
std::vector<int> primes{2, 3, 5, 7};  // starts with four elements
std::vector<int> zeros(5);            // five elements, all 0
std::vector<int> sevens(5, 7);        // five elements, all 7

More options for setting starting values are covered in c vector initialization.

Adding, reading and removing elements

This program adds three numbers and reads them back:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;
    numbers.push_back(10);   // add to the end
    numbers.push_back(20);
    numbers.push_back(30);

    std::cout << "Size: " << numbers.size() << "\n";   // 3
    std::cout << "First: " << numbers[0] << "\n";      // 10
    std::cout << "Last: " << numbers.back() << "\n";   // 30

    return 0;
}

Output:

Size: 3
First: 10
Last: 30

The everyday operations are:

  • push_back(value) adds an element to the end.
  • pop_back() removes the last element.
  • insert(position, value) and erase(position) add or remove an element at an iterator position. Elements after that point shift over, so these take longer on large vectors.
  • size() returns the number of elements, and empty() returns true when there are none.

Here is insert and erase in action:

std::vector<int> v{1, 2, 4};
v.insert(v.begin() + 2, 3);   // 1, 2, 3, 4
v.erase(v.begin());           // 2, 3, 4
v.pop_back();                 // 2, 3

Reading an element with numbers[i] does not check whether i is in range. The at() function does check, and it throws a std::out_of_range exception when the index is too big:

#include <iostream>
#include <stdexcept>
#include <vector>

int main() {
    std::vector<int> v{5, 6, 7};

    std::cout << v[1] << "\n";   // 6

    try {
        std::cout << v.at(10) << "\n";   // index 10 does not exist
    } catch (const std::out_of_range&) {
        std::cout << "Index out of range\n";
    }

    return 0;
}

Output:

6
Index out of range

Using an index that does not exist with [] is undefined behavior, so the program may crash or print a meaningless value.

Looping through the elements

A range-based for loop is the simplest way to visit every element:

for (int n : numbers) {
    std::cout << n << "\n";
}

An index-based loop also works:

for (std::vector<int>::size_type i = 0; i < numbers.size(); ++i) {
    std::cout << numbers[i] << "\n";
}

size() returns an unsigned type, so the index uses std::vector<int>::size_type. A plain int index can trigger sign-comparison warnings. For larger element types, for (const auto& item : items) avoids copying each element.

Size and capacity

size() counts the elements that are stored. capacity() is how many elements fit before the vector needs a bigger block of memory. reserve(n) makes room for at least n elements without changing size(). If you roughly know how many items you will add, calling reserve first can avoid several reallocations:

std::vector<int> v;
v.reserve(1000);                // capacity is at least 1000 now
std::cout << v.size() << "\n";  // 0, because no elements were added

Output:

0

resize(n) changes the number of elements instead. If the vector grows, the new int elements are set to 0.

Passing a vector to a function

Pass a vector by const reference when the function only needs to read it. The function can then read the caller’s vector without making a copy:

#include <iostream>
#include <vector>

int sum(const std::vector<int>& values) {
    int total = 0;
    for (int v : values) {
        total += v;
    }
    return total;
}

int main() {
    std::vector<int> nums{1, 2, 3, 4};
    std::cout << sum(nums) << "\n";   // 10
    return 0;
}

Output:

10

Passing a vector by value makes a full copy, which costs time and memory for large vectors. Passing a plain C array to a function follows different rules, which are covered in how to pass an array to a function in c.

How this compares with C arrays

A plain array has a size that is set when you declare it:

int nums[4] = {10, 20, 30, 40};   // size 4, fixed when declared

When the size needs to change while the program runs, C code usually allocates memory with malloc:

#include <stdlib.h>

int main(void) {
    int *nums = malloc(4 * sizeof *nums);   // room for 4 ints
    if (nums == NULL) {
        return 1;
    }

    nums[0] = 10;
    // ...use nums...

    free(nums);
    return 0;
}

Growing that block means calling realloc, checking the result, and keeping track of the size yourself. If realloc fails, it returns NULL. Assigning that result straight back to the same pointer then loses the old block. std::vector handles growing and size tracking for you.

Common mistakes

  • Reading past the end. Using numbers[5] on a three-element vector is undefined behavior. Check size() first, or use at(), which throws.
  • Using an element after the vector grows. push_back can move every element to a new block of memory. A reference, pointer or iterator to an element can then point to memory that is no longer valid:
std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4);   // may reallocate the elements
// first may no longer be valid here
  • Calling front(), back() or pop_back() on an empty vector. Each one needs at least one element. Check empty() first.

When to use something else

std::vector is a common default for a growable list in C++. Two other standard containers can fit better in some cases:

  • For a fixed number of elements known at compile time, std::array is a lighter choice. The details are in c std::array.
  • If you often insert or remove elements in the middle and do not need index access, std::list may fit better. The standard linked list is covered in c std::list.

Keep exploring

Guides from other topics

All topics →

std::optional in C++

std::optional in C++17 holds either a value or nothing. Learn how to check it, read it safely with value_or and return it from a function, with examples.

std::optional 4 min read

NULL vs nullptr in C++

NULL is an older macro, usually defined as 0. nullptr, added in C++11, is a typed null pointer that avoids overload surprises. Here's how to choose.

Is C++ Hard to Learn?

Is C++ hard to learn? This guide explains which parts trip up beginners, how C++ compares with C, and a practical order for learning it step by step.

Is C++ Hard 5 min read