Skip to content

Guided Refactoring Test

How to write expressive C++ for the following problem?

is any of the numbers positive?
Step 1
bool is_any_positive = false;
for(int value : numbers) {
if (value > 0) {
is_any_positive = true;
break;
}
}
Step 2
bool is_any_positive = false;
for(int value : numbers) {
if (value > 0) {
is_any_positive = true;
break;
}
}
bool is_any_positive = std::any_of(
numbers.cbegin(),
numbers.cend(),
[](const int value) { return value > 0; });
}
Step 3
bool found = std::any_of(
numbers.cbegin(),
numbers.cend(),
[](const int value) { return value > 0; });
}
bool is_any_positive = std::ranges::any_of(numbers,
[](const int value) { return value > 0; });
Step 4
bool is_any_positive = std::ranges::any_of(numbers,
[](const int value) { return value > 0; });
const auto is_positive = [](const int value) { return value > 0; };
bool is_any_positive = std::ranges::any_of(numbers, is_positive);
Step 5
using std::ranges::any_of;
const auto is_positive = [](const int value) { return value > 0; };
bool is_any_positive = std::ranges::any_of(numbers, is_positive);
bool is_any_positive = any_of(numbers, is_positive);