In this C++ tutorial, you shall learn how to check if the vector contains given element, with example programs.

Check if Vector contains specified element in C++

To check if the vector contains specified element in C++, we can iterate over the elements of the vector and verify if the element of the vector at respective iteration is equal to the specified element.

The code to check if vector v1 contains the element e is

bool isElementPresent = false;
for ( auto& element : v1 ) {
   if ( element == e ) {
      isElementPresent = true;
      break;
   }
}

C++ Program

In the following program, we take an integer vector in v1 and check if the vector contains the element specified in variable e.

We will use Foreach loop statement to iterate over the elements of the vector v1, if-else statement to print the output: if the vector contains the specified element or not, and Equal-to comparison operator to check if two elements are equal.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
   //int vector
   vector<int> v1 { 2, 4, 6, 8, 10 };
   int e = 8;

   //check if vector v1 contains the element e
   bool isElementPresent = false;
   for ( auto& element : v1 ) {
      if ( element == e ) {
         isElementPresent = true;
         break;
      }
   }
   
   if ( isElementPresent ) {
      cout << "element is present in the vector.";
   } else {
      cout << "element is not present in the vector.";
   }
}

Output

element is present in the vector.
ADVERTISEMENT

Conclusion

In this C++ Tutorial, we learned how to check if the vector contains the specified element.