Simplify simple C ++ code - something like Pythons any

I now have this code:

bool isAnyTrue() {
    for(std::list< boost::shared_ptr<Foo> >::iterator i = mylist.begin(); i != mylist.end(); ++i) {
        if( (*i)->isTrue() )
            return true;
    }

    return false;
}

I used Boost here and then, but I couldn’t remember any simple way to write it, as if I could write it in Python, for example:

def isAnyTrue():
    return any(o.isTrue() for o in mylist)

Is there any construct in STL / Boost to write it more or less like this?

Or maybe the equivalent of this Python code:

def isAnyTrue():
    return any(map(mylist, lambda o: o.isTrue()))

Basically I am wondering if there is still an existing equivalent any(s all) in Boost / STL. Or why not (because it seems quite useful, and I use it quite often in Python).

+5
source share
3 answers

C ++ does not yet have a construct foreach. You must write this to yourself /

, std::find_if :

bool isAnyTrue()
{
    return std::find_if(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue))
           != mylist.end();
}

, , std::vector std::deque, std::list.

EDIT: sth , , shared_ptr ... - boost:

//#include <boost/ptr_container/indirect_fun.hpp>

bool isAnyTrue()
{
    return std::find_if(mylist.begin(), mylist.end(), 
           boost::make_indirect_fun(std::mem_fun(&Foo::isTrue))) != mylist.end();
}

. .

+6

find_if any. find_if, .

template<class ForwardIterator, class Pred>
bool any(ForwardIterator begin, ForwardIterator end, Pred pred) {
  for( ; begin != end; ++begin)
    if(pred(*begin)) return true;

  return false;

  //or
  //return std::find_if(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue))
  //       != mylist.end();

}

bool isAnyTrue() {
  return any(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue));
}

: find_if by Billy ONeal.

+4

++ std:: any_of, .

bool isAnyTrue()
{
    return std::any_of(mylist.begin(), mylist.end(), std::mem_fn(&Foo::isTrue)); // Note std::mem_fn and not std::mem_fun
}

VS2010 .

+4

All Articles