Open In App

How to Check if a Vector Contains a Given Element in C++?

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

In C++, a vector is a dynamic array that provides a resizable and efficient way to store elements. Vectors store their elements in contiguous memory locations, similar to arrays, which allows for efficient access and iteration.

In this article, we will go through various methods which help us how to check whether a vector contains a given element or not.

Example

Input:
myVector = {1, 7, 2, 9, 1, 6};
target = 9

Output:
The value 9 is present in the Vector

Check if a Vector Contains a Given Element in C++

To check whether an element is present in the vector or not, we can use the std::count method of STL that counts the number of occurrences of a value in the given range. If the count returns zero, then it means that the element is not present. If it returns non-zero value, then it means that the value is present in the vector.

C++ Program to Check if a std::vector Contains a Given Element

C++




// C++ program to check whether the given value is present
// in the vector or not.
#include <algorithm>
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Define a vector of doubles and a target value
    vector<double> values = { 1.5, 2.5, 3.5, 4.5 };
    double target = 3.5;
  
    // Count the occurrences of the target value in the
    // vector
    int cnt = count(values.begin(), values.end(), target);
  
    // Check if the target value was found
    if (cnt > 0) {
        cout << "Element found in vector.\n";
    }
    else {
        cout << "Element not found in vector.\n";
    }
  
    return 0;
}


Output

Element found in vector.

Time Complexity: O(n), where n is the number of elements in the vector.
Space Complexity: O(1)

We can also the the std::find function that can be used to find the first occurrence of the element in the given range. If the element is not present, this function returns the iterator to the end of the range.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads