How to Check if a Vector Contains an Element in C++

by | C++, Programming, Tips

This tutorial will go through how to find an element in a C++ vector and how to count the number of occurrences of an element with the help of code examples.


A Brief Introduction on Vectors in C++

A vector is a dynamic container for storing data. Unlike arrays, the size of a vector can grow and shrink dynamically during the execution of a program. Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program like so

#include <vector>

Let’s look at how to find elements in a C++ vector.

Find Element in C++ Vector Using std::find()

The function std::find() searches for an element equal to the value passed as a parameter and returns an iterator pointing to that element in the vector. The syntax of find() is as follows:

find(first, last, value)

Where first and last are the input iterators to the initial and final positions in a sequence. The function searches for value in all elements between first and last including the element pointed by first but not the element pointed by last.

Let’s look at an example where we want to find an integer in an array of integers.

#include <iostream>
#include <vector>

int find_element(std::vector<int> arr, int k){
    
    std::vector<int>::iterator it;
    
    it = std::find(arr.begin(), arr.end(), k);
    
    if(it != arr.end())
    
        return (it - arr.begin());
    
    else
    
        return -1;
}

In the above code, we will define a function that takes a vector and key to search for as parameters. We declare an iterator for our vector which points to the memory address of the vector. We use this iterator to traverse the vector. Then, we call std::find to return the position of key k in the vector. Using an if statement we return the position of the element if it exists in the vector otherwise we return -1 meaning it is not in the vector.

Let’s define a vector of int in the main() function and call the find_element to find the number 6.

int main() {

    std::vector<int> arr = {2, 4, 6, 8, 10};

    int k = 6;

    std::cout << find_element(arr, k) << std::endl;

}

Let’s run the code to get the result:

2

The number 6 is at position 2 in the vector.

You can test your C++ code using our free C++ compiler and code executor.

Return Index of the Element Using std::find_if()

We can find the index of an element in a vector using the std::find_if() function. This function finds the first element in a range for which the predicate function returns true. Let’s look at an example where use find_if() the first element in a vector of integers that is a multiple of 5.

#include <iostream>
#include <vector>

// Returns true if x is a multiple of 5

bool multipleOf5(int x) {

    return x % 5 == 0;

};

int main(){

    std::vector<int> arr = {2, 4, 6, 8, 10, 12, 20};

    std::vector<int>::iterator mult5 = std::find_if(arr.begin(), arr.end(), multipleOf5);

    std::cout << "First item that is a multiple of 5:  " << *mult5 << std::endl;

    return 0;
}

Count the Number of Occurrences of an Element Using std::count()

The function std::count() returns the number of occurrences of an element in a vector. The syntax of std::count is as follows:

count(first, last, value)

Where first and last are the input iterators to the initial and final positions in a sequence. The function searches for value in all elements between first and last, including the element pointed by first but not the element pointed by last.

Let’s look at an example:

#include <iostream>
#include <vector>

bool count_elements(std::vector<int> arr, int k){

    return std::count(arr.begin(), arr.end(), k);

}

In the above code, the function count_elements() takes a vector of int and a key as its parameters.

#include <iostream>
#include <vector>
bool count_elements(std::vector<int> arr, int k){

    return std::count(arr.begin(), arr.end(), k);

}

int main(){

    std::vector<int> arr = {2, 4, 6, 8, 10, 12};

    int k = 6;

    std::cout << count_elements(arr, k) << std::endl;

    return 0;

}
1

Return Boolean Using std::any_of()

The std::any_of function works similarly to the std::find_if() function. The any_of() function returns a boolean value True if the predicate returns True for any of the elements and False otherwise.

Let’s look at an example where use any_of() to check if any of the elements in a vector of integers is a multiple of 5.

#include <iostream>
#include <vector>

// Returns true if x is a multiple of 5
bool multipleOf5(int x) {

    return x % 5 == 0;

};

int main(){

    std::vector<int> arr = {2, 4, 6, 8, 10, 12, 20};

    if (std::any_of(v.begin(), v.end(), multipleOf5)) {

        std::cout << "Element found";

    }

    else {

        std::cout << "Element not found";

    }

    return 0;

}
Element found

Summary

Congratulations on reading to the end of this tutorial! We have gone through several ways to check if an element exists in a vector and how to count the number of occurrences of an element in a vector.

For further reading on C++, go to the articles:

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨