Searching for Multiple Occurrences of a Value in a Container
What is the best way to search for multiple occurrences of a value in a container using standard library algorithms?
To search for multiple occurrences of a value in a container, you can use a combination of std::ranges::find()
and a loop, or std::ranges::find_if()
if the search criteria are more complex.
Using a Loop with std::ranges::find()
One way to find all occurrences is to use std::ranges::find()
in a loop:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers{1, 2, 3, 2, 4, 2, 5};
int target = 2;
auto it = numbers.begin();
while ((it = std::ranges::find(
it, numbers.end(), target)) != numbers.end()) {
std::cout << "Found " << target
<< " at position " << std::distance(
numbers.begin(), it) << '\n';
++it; // Move to the next element
}
}
Found 2 at position 1
Found 2 at position 3
Found 2 at position 5
Explanation
- Use
std::ranges::find()
to find the first occurrence of the target value. - Move the iterator one position forward after each find to continue the search.
- Loop until no more occurrences are found.
Using std::ranges::find_if()
If you need to find occurrences based on a condition, use std::ranges::find_if()
:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers{1, 2, 3, 2, 4, 2, 5};
auto it = numbers.begin();
while ((it = std::ranges::find_if(
it, numbers.end(), [](int n) {
return n == 2;
})) != numbers.end()) {
std::cout << "Found 2 at position "
<< std::distance(numbers.begin(), it)
<< "\n";
++it; // Move to the next element
}
}
Found 2 at position 1
Found 2 at position 3
Found 2 at position 5
Explanation
- Use
std::ranges::find_if()
with a lambda function to specify the search condition. - Move the iterator forward after each find to continue searching.
Summary
Using a loop with std::ranges::find()
or std::ranges::find_if()
, you can effectively search for multiple occurrences of a value in a container.
This method allows you to handle simple equality checks or more complex conditions, making it a versatile approach for various search scenarios.
Search Algorithms
An introduction to the 8 main searching algorithms in the C++ standard library, including find()
, find_if()
, find_if_not()
, find_first_of()
, adjacent_find()
, search_n()
, search()
, and find_end()
.