FIND()

The find() function in C++ is used to search for a specific value or substring within a container or string. Its behavior depends on the context where it’s used. When applied to standard containers like std::vector, std::list, or std::array, it returns an iterator to the first occurrence of a given element, or the container’s .end() iterator if the element isn’t found. When used with strings (std::string::find()), it is a member function that returns the position index of the first occurrence of a substring or character, or std::string::npos if not found. This makes find() a versatile and essential function for efficiently locating elements or text.

InputIterator find(InputIterator first, InputIterator last, const T& value);

 * Searches the range [first, last) for the first element equal to value.
 * Returns an iterator pointing to the found element, or last if not found.
auto it = find(vectorName.begin(), vectorName.end(), value);

 * vectorName.begin(): Points to the first element in the vector (like a pointer to the first memory location)
 * vectorName.end(): Points just past the last element (used to mark the end of the vector)
 * value: The element you're searching for
 * it: This is the iterator (like a pointer) returned by find(). If the value is found, it points to that element. If not, it equals vectorName.end()
 * auto: Automatically figures out the correct data type for it, so you don't have to write the full iterator type manually
#include <iostream>
#include <vector>
#include <algorithm>  // For std::find
using namespace std;

int main() {
    // Step 1: Create a vector of numbers
    vector<int> numbers = {10, 20, 30, 40, 50};

    // Step 2: Search for the value 30
    auto it = find(numbers.begin(), numbers.end(), 30);

    // Step 3: Check if the value was found
    if (it != numbers.end()) {
        // Found: Calculate the index by subtracting begin() from the iterator
        cout << "Element found at index: " << it - numbers.begin() << endl;
        cout << "Value at the iterator is: " << *it << endl; // *it gives the actual value stored at that position

    } else {
        // Not found
        cout << "Element not found." << endl;
    }

    return 0;
}

OUTPUT:
 Element found at index: 2
 Value at the iterator is: 30

Last updated