Searching elements
Finding elements in a collection is as crucial as storing them. In the C++ STL, there’s a buffet of algorithms tailored for searching. Whether std::vector
is sorted or unsorted, the STL provides an array of functions that’ll lead you straight to your target using the classic linear or faster binary search. With std::vector
, these techniques become indispensable in many scenarios.
Linear search with std::find
The most basic and intuitive searching algorithm is the linear search. If you’re not sure about the order of your vector or it is simply unsorted, this method comes to the rescue.
Consider std::vector<int> numbers = {21, 12, 46, 2};
. To find the position of the element 46
, we will use the following code:
auto it = std::find(numbers.begin(), numbers.end(), 46);
If the element exists, it will point to its location; otherwise, it’ll point to numbers.end()
. It’s a direct, no-frills approach, checking each element...