Horje
How to Access Vector Element Using Iterator in C++?

In C++, vectors are container that works like a dynamic array. STL provides iterators for the traversal of these containers. In this article, we will learn how to access an element in a vector using an iterator in C++.

Example

Input:
myVector = {1, 5, 8, 1, 3, 4}

Output:
myVector value at index 5 using iterator: 4

Access Element in a Vector Using Iterator in C++

Iterators work like a pointer to the elements. We first get the iterator to the beginning (or first element) of the vector using the std::vector::begin() function. Then we add the index of the element that we want to access and dereference it like a pointer using the dereferencing operator.

C++ Program To Access Vector Element Using Iterator in C++

C++

// C++ Program to access array elements using an iterator
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Declare and initialize a vector.
    vector<int> v = { 6, 1, 5, 3, 2, 7 };
  
    // Declare and initialize a iterator pointing at the
    // beginning of the vector.
    auto itr = v.begin();
  
    // accessing element using iterator
    cout << "Element at Index 4: " << *(itr + 4) << endl;
    return 0;
}

Output

Element at Index 4: 2

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




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Increase the Capacity of a Vector in C++? How to Increase the Capacity of a Vector in C++?
Find All Occurrences of an Element in a Vector Find All Occurrences of an Element in a Vector
How to Find the Size of a Vector in C++? How to Find the Size of a Vector in C++?
How to Find a Pair by Key in a Vector of Pairs in C++? How to Find a Pair by Key in a Vector of Pairs in C++?
How to Compare Two Pairs in C++? How to Compare Two Pairs in C++?

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