Skip to main content

Introduction to Vectors

Today, let's talk about one of the most powerful and commonly used features in C++ — vectors.

A vector is basically a resizable array, meaning it can grow or shrink automatically depending on how many elements you add or remove. Unlike normal arrays in C++—whose size cannot be changed once declared—vectors give us flexibility and safety.


To use a vector, we simply include the <vector> header and then write

vector<type> name;

For example:

vector<int> scores = {85, 90, 78};


Vectors are part of the Standard Template Library, also known as STL, which provides ready-made data structures like vectors, stacks, queues, sets, and maps. STL makes programming faster and reduces errors because the functions are well-tested and optimized.


Now, one of the most important operations in a vector is push_back(), which adds an element to the end of the vector in constant time—meaning it’s very efficient. We can also insert elements at any position using insert(position, value).


Accessing elements is simple too. We can use

v[i] for direct access or v.at(i) when we want bounds checking.

The at() function is safer because it gives an error if the index is out of range, while v[i] may cause undefined behavior.


Updating an element is done using the assignment operator, like v[1] = 500; It directly replaces the old value at that index. Vectors also allow us to check their size using v.size() and traverse all elements using loops.


“Now let’s continue with more useful vector operations.

If you want to know how many elements are currently inside the vector, you use size(), but if you want to check the amount of memory allocated, you use capacity().

You can also check if a vector is empty by using empty(), and you can remove the last element using pop_back().


+Vectors support operations like resize(n) to change their size, clear() to remove all elements, and front() or back() to access the first or last element.

To completely replace the contents of a vector, we can use assign(n, x), which fills the vector with n copies of the value x.

There’s also swap(v2) which exchanges the contents of two vectors instantly.


Here’s an example:

If we have a vector and want to insert or erase elements, we can simply use

insert(v.begin() + pos, value)

or

erase(v.begin() + pos)

which allow precise control over where elements go.


Finally, vectors are extremely useful in real programs. For example, calculating the average of N numbers, storing characters, or building dynamic data structures. With features like safety, flexibility, and a rich set of functions, vectors are considered one of the most important containers in modern C++ programming.

And that’s a complete overview of C++ vectors — their purpose, operations, and why they’re so essential in everyday coding.


Comments