Check if an element exists in vector in C++
Hey folks! Here, we are going to check if an element exists in a vector or not in C++. In general, you can find element in a vector using std functions. This returns an iterator to the element of it’s first occurrence.
Algorithm:
Here, we are going to discuss two methods.
- Looping through vector
- Using std::find() method
Syntax:
Vector : vector<int>v;
Iteration : for(auto it:v){}
Find method : Iterator find (Iterator firstElement, Iterator lastElement, int val);
{where iterator = vector<int>:: iterator it;C++ program to check if an element exists in vector
#include<bits/stdc++.h>
using namespace std;
int main ()
{
std::vector<int> v { 1, 2 , 3, 4 };
// Method 1: Iterating over vector
// The element that will be searched
int ele1 = 3;
bool found = false;
for(auto it:v){
if(it==ele1){
cout<<"Element " <<ele1<< " discovered ."<<endl;
found = true;
break;
}
}
if(!found)
cout<<"Element not found."<<endl;
// Method 2: Using std::find() function
// The element that will be searched
int ele = 5;
if (std::find(v.begin(), v.end(), ele) != v.end())
cout<<"Element " <<ele<< " discovered .";
else
cout<<"Element not found.\n";
return 0;
}Time Complexity:
Both functions take O(N) time complexity as iteration is done all over the vector in the worst case and std function too.
Output:
Element 3 discovered. Element not found.
Also read: How to remove elements from a vector inside a loop in C++
Leave a Reply