Open In App

How to Access Elements in a Vector in C++?

Last Updated : 20 Nov, 2024
Comments
Improve
Suggest changes
2 Likes
Like
Report

In C++, vector provides fast access to its elements using their position as indexes. In this article, we will discuss different ways to access the element in vector using index in C++.

The simplest method to access the elements of vector is by using vector operator [] with the corresponding index value. Let’s take a look at a simple example:


Output
d

Explanation: Indexes of vectors in C++ starts from 0 and goes till (size - 1). This method does check whether the given index exists in the std::vector or not leading undefined behaviour if the index is invalid.

There are also some other methods in C++ by which we can access

Using Vector at()

Vector elements can also access using vector::at() method. This method also takes the index but if the index is invalid it throws std::out_of_range exception.


Output

d
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 5)

Explanation: The element at index 3 is accessed without any problem, but when we tried to access the element at index 10, we got the out-of-range error.

Using Iterators

Iterators are like pointers to the elements of the vector which can be deference to access the element it points to. The vector begin() functions returns iterator to the first element. It can be incremented to point to the element at desired index.

Syntax

v.begin() + idx;

where, idx is the index whose value to be accessed.


Output
21

This method also does not perform bound checking.

Using Vector front()

The vector front() method can be used to quickly access the first element of the vector without bothering about index.


Output
a

Make sure that the vector is not empty while using vector front() method, otherwise it may cause segmentation fault.

Using Vector back()

Just like vector front() method, vector back() method can be used to quickly access the last element of the vector without bothering about index.


Output
z

Next Article
Article Tags :
Practice Tags :

Similar Reads