How to Access an Element in a Vector Using Index in C++?
Last Updated :
08 Feb, 2024
In C++, vector containers are dynamic arrays that can adjust their size automatically according to the number of elements they are storing. In this article, we will see how to get the element in a vector using the specified position in C++
Example
Input:
myVector = {1, 2, 3, 4, 5}
Output:
Element at index 3 is 4
Access an Element in a Vector using an Index in C++
Similar to arrays, vectors also follow the 0-based indexing in C++, where the index starts from 0 and goes till n-1 where n is the total number of elements in the vector.Â
Vector Indexing
We can use the array subscript operator [] with the index value inside them to access the vector element in C++ in a similar way to arrays.
C++ Program Access an Element in a Vector using an Index
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 10, 20, 30, 40, 50, 60, 70 };
cout << "Vector: " ;
for ( int num : vec) {
cout << num << " " ;
}
cout << endl;
int index = 4;
if (index >= 0 && index < vec.size()) {
cout << "Element at index " << index
<< " is: " << vec[index] << endl;
}
else {
cout << "Invalid index." << endl;
}
return 0;
}
|
Output
Vector: 10 20 30 40 50 60 70
Element at index 4 is: 50
Time Complexity : O(1)
Auxiliary Space : O(1)
Share your thoughts in the comments
Please Login to comment...