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.
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
std::ranges::find()
to find the first occurrence of the target value.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
std::ranges::find_if()
with a lambda function to specify the search condition.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.
Answers to questions are automatically generated and may not have been reviewed.
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()
.