Open In App

How to Find the First Occurrence of an Element in a Vector?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the vector is a dynamic array that is defined in the STL template library inside the <vector> header. In this article, we will learn how to find the first occurrence of a specific element in a vector in C++.

For Example

Input:
vector<int>v = {5, 7, 1, 2, 3, 7, 1}
Target = 1
Output:
The first occurrence of 1 is at index: 2

Find the First Occurrence of a Specific Element in a Vector

To find the first occurrence of a specific element in a std::vector, use the std::find() method that is part of the <algorithm> header and it returns an iterator that points to the first occurrence of the target element, if it is present in the vector otherwise it returns the iterator pointing to the end of the vector.

C++ Program to Find the First Occurrence of a Specific Element in a Vector

The below program demonstrates the use of the find() function to find the first occurrence of a specific element in a given vector.

C++




// C++ Program to Find the First Occurrence of a Specific
// Element in a Vector
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // initializing vector
    vector<int> v = { 5, 7, 1, 2, 3, 7, 1 };
    // target whose first occurence need to be searched
    int target = 1;
  
    // calling find() method to find the first occurrence of
    // the element in the vector.
    auto it = find(v.begin(), v.end(), target);
  
    // if target is found print it's index
    if (it != v.end()) {
        cout << "The first occurrence of " << target
             << " is at index: " << it - v.begin() << endl;
    }
    // else element not found
    else {
        cout << "Element not found." << endl;
    }
  
    return 0;
}


Output

The first occurrence of 1 is at index: 2

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads