Find Elements Using STL Algorithms
In this step, you'll learn how to use STL algorithms to find and search for elements in containers. The <algorithm>
library provides powerful functions for searching and locating elements.
Open the WebIDE and create a new file called find_demo.cpp
in the ~/project
directory:
touch ~/project/find_demo.cpp
Add the following code to the find_demo.cpp
file:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Create a vector of integers
std::vector<int> numbers = {5, 2, 8, 1, 9, 3, 8};
// Find first occurrence of a specific element
auto it = std::find(numbers.begin(), numbers.end(), 8);
if (it != numbers.end()) {
std::cout << "First occurrence of 8 at index: "
<< std::distance(numbers.begin(), it) << std::endl;
}
// Count occurrences of an element
int count = std::count(numbers.begin(), numbers.end(), 8);
std::cout << "Number of 8s in the vector: " << count << std::endl;
// Find if any element is greater than 6
bool has_large_element = std::any_of(numbers.begin(), numbers.end(),
[](int n) { return n > 6; });
std::cout << "Vector has element > 6: "
<< (has_large_element ? "Yes" : "No") << std::endl;
// Find the minimum and maximum elements
auto min_it = std::min_element(numbers.begin(), numbers.end());
auto max_it = std::max_element(numbers.begin(), numbers.end());
std::cout << "Minimum element: " << *min_it << std::endl;
std::cout << "Maximum element: " << *max_it << std::endl;
return 0;
}
Compile and run the program:
g++ find_demo.cpp -o find_demo
./find_demo
Example output:
First occurrence of 8 at index: 2
Number of 8s in the vector: 2
Vector has element > 6: Yes
Minimum element: 1
Maximum element: 9
Key points about STL search algorithms:
std::find()
locates first occurrence of an element
std::count()
counts element occurrences
std::any_of()
checks if any element meets a condition
std::min_element()
and std::max_element()
find extreme values
- Lambda functions can be used for custom search conditions
- Return iterators point to found elements