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.
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++ Program to demonstrate vector initialization and // accessing elements by index #include <iostream> #include <vector> using namespace std;
int main()
{ // Initialize a vector
vector< int > vec = { 10, 20, 30, 40, 50, 60, 70 };
// Print the vector elements
cout << "Vector: " ;
for ( int num : vec) {
cout << num << " " ;
}
cout << endl;
// Declare the index of the vector you want to access
int index = 4;
// check if the index is valid -- the valid range for
// index is 0 - n-1
if (index >= 0 && index < vec.size()) {
cout << "Element at index " << index
<< " is: " << vec[index] << endl;
}
else {
cout << "Invalid index." << endl;
}
return 0;
} |
Vector: 10 20 30 40 50 60 70 Element at index 4 is: 50
Time Complexity : O(1)
Auxiliary Space : O(1)