Search⌘ K

Vectors

Explore the use of std::vector in C++, focusing on its dynamic resizing, memory handling through size and capacity methods, and safe element access. Understand how to construct, modify, and manage vectors effectively as part of sequential containers.

We'll cover the following...

std::vector is a homogeneous container, for which it’s length can be adjusted at runtime. std::vector needs the header <vector>. As it stores its elements contiguously in memory, std::vector supports pointer arithmetic.

C++
for (int i= 0; i < vec.size(); ++i){
std::cout << vec[i] == *(vec + i) << std::endl; // true
}

Make sure to distinguish the round and curly braces in the creation of an std::vector

If we construct a std::vector, we mustkeep a few things in mind. The constructor with round braces in the following example creates an std::vector with a capacity of 10 elements, while the constructor with curly braces creates an std::vector with the element 10.

std::vector<int> vec(10);
std::vector<int> vec{10};

The same rules hold true for the expressions std::vector<int>(10, 2011) ...