How to Access First Element in a Vector Using Iterator in C++?

In C++, vectors are containers similar to arrays but unlike arrays, vectors can resize themselves during the runtime. These vectors provide iterators to access their elements. In this article, we will learn how to access the first element in a vector using an iterator in C++.

Example

Input:
myVector = {10,20,30,40,50}

Output:
The first element of the vector is : 10

Retrieving First Element of a Vector Using Iterator in C++

To access the first element of a std::vector using an iterator, we can use the std::vector::begin() function which returns the iterator to the first element in the vector. Then we can dereference this iterator using the dereferencing (*) operator to get the value of the first element stored in the vector.

C++ Program to Retrieve First Element of a Vector Using Iterator

The following program illustrates how we can access the first element in a vector using an iterator in C++.

C++
// C++ Program to how to access the first element in a
// vector using an iterator
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Initializing a vector
    vector<int> vec = { 10, 20, 30, 40, 50 };

    // Obtain an iterator pointing to the beginning of the
    // vector
    vector<int>::iterator it = vec.begin();
    // Access the first element of the vector  using the
    // iterator

    int first_element = *it;
    // Print the first element of the vector
    cout << "The first element of the vector is: "
         << first_element << endl;
    return 0;
}

Output
The first element of the vector is: 10

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




Contact Us