如何在C ++ 98中实现map,filter,fold

时间:2015-04-06 16:47:20

标签: c++ functional-programming c++98

我希望能够做到这样的事情:

std::list<Person> personList;

std::list<Person> filteredPersonList;

Person filterByAge(Person p){
  if(p.age >= 18) return p;
}

filteredPersonList = filter(personList, filterByAge)

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找remove_copy_if

std::list<Person> personList;

std::list<Person> filteredPersonList;

Person filterByAge(Person p){
  if(p.age >= 18) return false;
}

std::remove_copy_if(personList.begin(), personList.end(), std::inserter(filteredPersonList, filteredPersonList.end()), filterByAge);

答案 1 :(得分:0)

仅供记录:

template< 
        class IN_TYPE, 
        template < class IN_TYPE, class A = std::allocator< IN_TYPE > > class COLLECTION
> COLLECTION< IN_TYPE > filter (const COLLECTION< IN_TYPE >& collection, bool (*f) ( const IN_TYPE& ) )
{
    COLLECTION< IN_TYPE > result;

    typename COLLECTION< IN_TYPE >::const_iterator it;

    //std::copy_if( collection.begin(), collection.end(), result.begin(), f );
    for( it = collection.begin() ; it != collection.end() ; ++it )
    {
        IN_TYPE node = *it;
        bool passedFilter = f(node);

        if (passedFilter)
            result.push_back(node);
    }

    return result;
}