How to locate a specific element in a vector?

You can use the std::find function to locate the position of a specific 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 element = 3; // 要查找的元素

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

    return 0;
}

In the example above, we first define a vector of integer type and specify the element to be searched as 3. Then, we use the std::find function to search for this element in the vector. If found, we output the position of the element in the vector; otherwise, we output a message indicating that it was not found.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds