How to Check If All Elements in a Range Satisfy a Specific Condition in C++

How can I check if all elements in a range satisfy a specific condition?

To check if all elements in a range satisfy a specific condition in C++, you can use the std::all_of() algorithm from the <algorithm> header.

This function returns true if the provided predicate is satisfied by all elements in the range [first, last), and false otherwise.

Here's an example:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
  std::vector<int> numbers {2, 4, 6, 8, 10};

  bool all_even = std::all_of(
    numbers.begin(), numbers.end(), [](int num) {
      return num % 2 == 0;
    }
  );

  if (all_even) {
    std::cout << "All numbers are even.";
  } else {
    std::cout << "Not all numbers are even.";
  }
}
All numbers are even.

How It Works

  • Including the Header: Include the <algorithm> header to access the std::all_of() function.
  • Using std::all_of(): This function takes three parameters: the beginning and end of the range, and a unary predicate that returns true for elements that satisfy the condition and false otherwise.

Practical Uses

  • Validation: std::all_of() is commonly used to validate that all elements in a container meet a certain criterion, such as checking if all numbers are positive, all strings are non-empty, or all objects in a collection have a specific property.
  • Early Exit: std::all_of() stops processing as soon as it finds an element that does not satisfy the predicate, making it efficient for large datasets where early exit can save processing time.

Example: Checking Custom Conditions

You can check any custom condition by providing the appropriate lambda function or functor. Here's an example checking if all elements are greater than a certain value:

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
  std::vector<int> numbers{5, 7, 9, 11};

  bool all_greater_than_five = std::all_of(
    numbers.begin(), numbers.end(), [](int num) {
      return num > 5;
    }
  );

  if (all_greater_than_five) {
    std::cout
      << "All numbers are greater than five.";
  } else {
    std::cout
      << "Not all numbers are greater than five.";
  }
}
Not all numbers are greater than five.

Conclusion

The std::all_of() algorithm is a powerful tool for validating ranges of elements against specific conditions. It simplifies the code and enhances readability while providing efficient performance.

Whether you are validating user input, processing data, or implementing business rules, std::all_of() can be a valuable addition to your toolkit.

Iterator and Range-Based Algorithms

An introduction to iterator and range-based algorithms, using examples from the standard library

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

How to Reverse the Order of Elements in a Vector Using the C++ Standard Library
How can I reverse the order of elements in a vector using the C++ standard library?
Difference Between std::sort() and std::stable_sort()
What is the difference between std::sort() and std::stable_sort()?
How to Remove Duplicates from a Sorted Vector in C++
How do I remove duplicates from a sorted vector in C++?
Finding the Smallest and Largest Elements in a Range in C++
What is the best way to find the smallest and largest elements in a range?
Using std::ranges Algorithms with C-Style Arrays
Can I use std::ranges algorithms with C-style arrays?
How to Debug Iterator and Range-Based Algorithm Issues in C++
What is the best way to debug iterator and range-based algorithm issues in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant