C++ STL: std::none_of

Michael Spagna
3 min readApr 18, 2021
C++ 20

Info

std::none_of checks to see if a given unary predicate returns false for all of the values in a range

Complexity: Linear, O(n)

Category: Non-Modifying Sequence Operations

Breakdown

std::none_of:

template<class InputIterator, class Predicate>
constexpr bool none_of(InputIterator first
,InputIterator last
,Predicate pred);

Parameters

  • first = Input Iterator to the start of the range
  • last = Input Iterator to the end of the range
  • pred = A unary predicate where pred(x) is a boolean value. Where x is a value in the range [first,last)

Returns

  • true if pred(x) returns false for all values in range [first,last)
  • false if pred(x) returns true for any value in range [first,last)

std::ranges::none_of:

template<ranges::input_range Range, class Predicate>
constexpr bool none_of(Range &&r, Predicate pred);

Parameters

  • r = The range to operate on (i.e. std::vector, std::set, ect.)
  • pred = A unary predicate where pred(x) is a boolean value. Where x is a value in range r

Returns

  • true if pred(x) returns false for all values in range r
  • false if pred(x) returns true for any values in range r

Use Cases

  • Checking that all values are not positive/negative, odd/even
  • Checking that a certain string is not present
  • Checking that all strings are less than a certain length

Examples

#include <algorithm>
#include <list>
#include <string>
#include <iostream>
int main()
{
std::list<int> l1({12, 9, 2, -3, 65});
std::list<std::string> l2({"dog", "cat", "bear", "xylophone"});
//Iterator none_of, returns true if no value is less than 0
bool positive = std::none_of(l1.begin()
,l1.end()
,[](int x)->bool
{return x<0;});
//Ranges none_of, returns true if no value is "fish"
bool missing = std::ranges::none_of(l2,[](std::string s)->bool
{return s=="fish";});
//Iterator none_of, returns true if no value is longer than 5
bool len = std::none_of(l2.begin()
,l2.end()
,[](std::string s)->bool
{return s.size()>=5;});
std::cout << "positive: " << positive << '\n';
std::cout << "missing: " << missing << '\n';
std::cout << "len: " << len << '\n';
}
Output
positive: 0
missing: 1
len: 0

Keywords

  • Input Iterator: Iterator used to read values from a container. Can only be used in sequential input operations. Each value it points to is read once then the iterator is incremented.
  • Lambda Function: Convenient way of defining an annonymous function right where it is used or passed as an argument. A simplified format, [lambda introducer](parameter)->return type{body;}
  • Non-Modifying Sequence Operation: An algorithm that does not modify the values in the container. It just reads every value in the container.
  • Predicate: Function that returns a boolean.
  • Range: A group of items you can iterate over.
  • Unary: A single input.

Sources

--

--

Michael Spagna
0 Followers

Im just here to learn some things