How to find a specified element in a vector in C++?

In C++, you can utilize the std::find algorithm to locate the position of a specified element in a vector. Here is an example code:

#include <iostream>
#include <vector>
#include <algorithm>

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

    int target = 3;

    auto it = std::find(vec.begin(), vec.end(), target);

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

    return 0;
}

In the code above, we define a vector called vec, and then use the std::find algorithm to locate the position of the element 3 in the vector. If the element is found, its index will be displayed; if it is not found, a message will be displayed.

bannerAds