Cover Image for Find Member Function in Vector in C++
92 views

Find Member Function in Vector in C++

The C++ can use the std::find() member function to search for an element in a vector. The std::find() function is part of the C++ Standard Library and is included in the <algorithm> header. It works for any type of container, including vectors.

Here’s how to use std::find() with a vector:

C++
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    int target = 3; // The element to search for

    // Use std::find to search for the target element in the vector
    std::vector<int>::iterator it = std::find(numbers.begin(), numbers.end(), target);

    if (it != numbers.end()) {
        std::cout << "Element found at index: " << std::distance(numbers.begin(), it) << std::endl;
    } else {
        std::cout << "Element not found in the vector." << std::endl;
    }

    return 0;
}

In this example:

  1. We create a std::vector<int> named numbers and populate it with some integers.
  2. We define a target variable that represents the element we want to find in the vector.
  3. We use std::find(numbers.begin(), numbers.end(), target) to search for the target element within the vector. The std::find() function returns an iterator pointing to the found element, or numbers.end() if the element is not found.
  4. We check if the iterator is equal to numbers.end() to determine if the element was found. If it was found, we use std::distance() to calculate the index of the found element.

You can use this approach to search for elements of any type in a vector or any other container supported by the C++ Standard Library.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS