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

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.




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Create a Map with Vectors as Keys and Sets as Values? How to Create a Map with Vectors as Keys and Sets as Values?
How Can I Sort a Map by Values in C++? How Can I Sort a Map by Values in C++?
How to Concatenate Two Vectors in C++? How to Concatenate Two Vectors in C++?
How to Initialize a Deque from a Vector in C++? How to Initialize a Deque from a Vector in C++?
How to Find the Intersection of a Vector and a Set in C++? How to Find the Intersection of a Vector and a Set in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14