Why am I not able to filter properly with drop_while?

60 views Asked by At

With respect to the following code:

static constexpr auto v = {0, 1, 2, 3, 4, 5};
for (int n : v | std::views::drop_while([](int i) { return i < 3; }))
   std::cout << n;
std::cout << n << ' ';

I am getting the expected output:

3 4 5

However, when I change the less than (<) to greater than(>) inside the Lambda function, why am I getting the output:

0 1 2 3 4 5

What's the functionality of the OR operator (|) in this case?

1

There are 1 answers

1
康桓瑋 On BEST ANSWER

From cppreference's description for drop_while:

A range adaptor that represents view of elements from an underlying sequence, beginning at the first element for which the predicate returns false.

When you change the condition of the lambda, since the first element does not satisfy the predicate, no elements are filtered.

What you want is views::filter, which will filter out all elements that don't satisfy the predicate.