Horje
How to Access an Element in a Vector Using Index in C++?

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

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++

// 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;
}

Output

Vector: 10 20 30 40 50 60 70 
Element at index 4 is: 50

Time Complexity : O(1)
Auxiliary Space : O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Delete an Element from a Priority Queue in C++ ? How to Delete an Element from a Priority Queue in C++ ?
How to Create a Template Class in C++? How to Create a Template Class in C++?
How to Create a Pure Virtual Function in C++? How to Create a Pure Virtual Function in C++?
How to Dynamically Allocate Memory for an Array of Strings? How to Dynamically Allocate Memory for an Array of Strings?
How to Overload the Function Call Operator () in C++? How to Overload the Function Call Operator () in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13