SoFunction
Updated on 2025-04-13

c++ vector Use find to find the specified element method

In C++,std::vectoris a dynamic array used to store sequences of elements of the same type. If you want tostd::vectorFind the specified element in  , you can usestd::findalgorithm.std::findIt is defined in<algorithm>Standard library functions in header files.

The following is a sample code that shows how to use itstd::findexiststd::vectorFind the specified element in  :

#include &lt;iostream&gt;
#include &lt;vector&gt;
#include <algorithm> // Include std::find
int main() {
    // Create a vector and initialize some elements    std::vector&lt;int&gt; vec = {1, 2, 3, 4, 5};

    // Element to be found    int target = 3;

    // Use std::find to find elements    auto it = std::find((), (), target);

    // Check whether the element is found    if (it != ()) {
        std::cout &lt;&lt; "Element" &lt;&lt; target &lt;&lt; " Found in location: " &lt;&lt; std::distance((), it) &lt;&lt; std::endl;
    } else {
        std::cout &lt;&lt; "Element" &lt;&lt; target &lt;&lt; " not found" &lt;&lt; std::endl;
    }

    return 0;
}

Code description:

Includes header files:

  • #include <iostream>: Used for input and output operations.
  • #include <vector>: Used for usestd::vector
  • #include <algorithm>: Used for usestd::find

Initializationstd::vector

  • std::vector<int> vec = {1, 2, 3, 4, 5};: Create a 5 integerstd::vector

Define the target element:

  • int target = 3;: Define the target element to be found.

usestd::findFind elements:

  • auto it = std::find((), (), target);: Callstd::find, incomingvectorThe start iterator, end iterator and target value of  .itWill point to the found element or()(If not found).

Inspection results:

  • if (it != ()): Check whether the iterator is equal to(), If not, it means that the target element has been found.
  • std::distance((), it): Calculate the position index of the found element.
  • If no element is found, the corresponding prompt information is output.

Notes:

  • std::findIt is a linear search algorithm with a time complexity of O(n), where n isvectorSize.
  • ifvectorContains a large number of elements and search operations are very frequent. You can consider using other data structures (such asstd::unordered_setorstd::set) to improve search efficiency.

In this way, you canstd::vectorEffectively find the specified element in  .

This is the article about c++ vector using find to find the specified element method. For more related c++ vector using find to find the content of specified element, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!