Data Structures

C++ Vectors

Working with Vectors

C++ vectors use std::vector for dynamic arrays.

Introduction to C++ Vectors

C++ Vectors, part of the Standard Template Library (STL), are dynamic arrays that allow you to store elements in a contiguous memory space. Unlike traditional arrays, vectors can resize themselves automatically when elements are added or removed.

Creating a Vector

To create a vector in C++, you need to include the <vector> header. You can declare a vector like this:

Adding Elements to a Vector

You can add elements to a vector using the push_back() method. This adds an element to the end of the vector:

Accessing Vector Elements

Vector elements can be accessed using the [] operator or the at() method. Here is an example of both:

Removing Elements from a Vector

To remove elements from a vector, you can use the pop_back() method, which removes the last element:

Vector Size and Capacity

Vectors manage two important properties: size and capacity. The size is the number of elements in the vector, while the capacity is the amount of storage currently allocated for the vector. Here is how you can access these properties:

Resizing a Vector

The resize() method allows you to change the number of elements stored in the vector. If the new size is greater than the current size, new elements are default-initialized. If it's less, elements are removed:

Clearing a Vector

To remove all elements from a vector, use the clear() method. This method sets the size of the vector to 0 but does not change its capacity:

Previous
Arrays
Next
Maps