C++ Logo

std-proposals

Advanced search

Re: Missing logical identity in <functional>

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Sun, 25 Aug 2019 11:25:57 -0400
On Sun, Aug 25, 2019 at 8:50 AM Miguel Ojeda via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Sun, Aug 25, 2019 at 2:17 PM Alexander Klein via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
> >
> > the other day I was trying to test whether all of the bits in a
> > std::vector< bool > were set or unset, but I couldn't come up with a
> > really elegant solution using the logical operations in <functional>,
> > because there seems to be no logical identity.
> >
> > In short, given
> >
> > std::vector< bool > v;
> >
> > I think it should be possible to write:
> >
> > bool all_set = all_of(v.cbegin(),
> v.cend(), std::logical_identity<bool>());
>
> An alternative in C++20 is:
>
> all_of(v.cbegin(), v.cend(), identity())
>

Or in C++11, using fewer template instantiations,

    bool all_set = std::all_of(v.begin(), v.end(), [](bool b){ return b; });

Or for smart-alecks,

    bool all_set = std::none_of(v.begin(), v.end(),
std::logical_not<bool>());

    bool all_set = std::accumulate(v.begin(), v.end(), true,
std::logical_and<bool>());

    bool all_set = std::accumulate(v.begin(), v.end(), 0, std::plus<int>())
== v.size();

    bool all_set = std::find(v.begin(), v.end(), false) == v.end();

–Arthur

Received on 2019-08-25 10:28:35