Depending on your exact requirements, consider std::stable_partition (or std::partition ). It reorders the elements in the range so that all that satisfy the predicate are first. You can think of it as dividing a range into a "subset" and "not a subset." Here is an example:
#include <algorithm> #include <vector> #include <iostream> int main() { using std::begin; using std::end; using std::cbegin; using std::cend; std::vector<int> ints { 1, 9, 3, 27, 5, 19, 3, 8, 2, 12 }; auto const greater_than_7 = [](int number) { return number > 7; }; auto const iter_first_not_greater_than_7 = std::stable_partition(begin(ints), end(ints), greater_than_7); for (auto const_iter = cbegin(ints); const_iter != iter_first_not_greater_than_7; ++const_iter) { std::cout << *const_iter << "\n"; } }
If, however, everything is OK with copying each corresponding item to a new collection, for example, because the original range should not be changed, then use std::copy_if .
Perhaps what you are really looking for is a representation of the unmodifiable range. In this case, you are approaching the problem from the wrong direction. You do not need a specific algorithm; A more natural solution to the problem would be filtering an iterator , such as Boost Filter Iterator . You can use it in Boost or study its implementation to find out how you can write filter iterators yourself.
Christian hackl
source share