A Vector in C++ is a kind of Dynamic Arrays. It is one of the most used STL Container. In this article, we will compare two different ways to access vector elements elements based on an index. The way we access them can make a difference in terms of safety and performance.

Access Vector Elements using Subscript Operator []

The subscript operator allows us to access an element of a vector based on its index position. Like this,

std::vector<int> numbers = {11, 22, 33, 44, 55};

// Access element at index 2 i.e. 3rd element of vector
int num = numbers[2];

std::cout << num << std::endl;  // Outputs: 33

This code fetches the element at index position 2 (i.e., the third element) from vector object numbers and prints it. Remember, vector indexing starts from 0, so the third element is at index 2.
It returns a reference of the selected vector element, so we can use it to modify the vector contents too.

However, there’s a concern with this approach. If we pass an index that doesn’t exist in the vector, it results in undefined behavior, which can be detrimental:

int value = numbers[200];  // Undefined behaviour!

The above code tries to access the element at index 200, which doesn’t exist in our vector. This could lead to a crash, returning a garbage value, or even corrupting other data structures, basically it can result in undefined behaviour, but it will not give any error upfront. It is like a silent bug.

Access Vector Elements using at() function

To tackle the problem of potential out-of-range access, vectors in C++ also offer the at() function:

// Access element at index 3 i.e. 4th element of vector
int value = numbers.at(3);

std::cout << value << std::endl;  // Outputs: 44

This function operates just like the subscript ([]) operator but with an added safety measure – it checks the range. If an invalid index is passed, the at() function doesn’t just produce undefined behavior. Instead, it throws an out_of_range exception:

try {
    int value = numbers.at(300);  // Throws an exception
} catch(const std::out_of_range& e) {
    std::cout << e.what() << std::endl;  // Outputs a detailed error message
}

The code attempts to access the element at index 300, which is beyond the size of the vector. The at() function recognizes this and throws an exception, which we catch and handle.

at() function vs [] Operator – Which one to choose?

While the at() function is safer than the subscript operator because of its range-checking, it’s slightly slower for the same reason. So the choice boils down to your needs:

  • If performance is crucial and you’re sure of the validity of indices, opt for the subscript operator.
  • If you want to ensure safety against potential out-of-bounds access, go with the at() function.

Summary

In conclusion, vectors offer flexible ways to access their elements, each with its trade-offs. It’s essential to understand these mechanisms to make informed choices in your C++ coding journey.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.