mercredi 2 novembre 2016

Python-like map in c++

My problem with std:: transform is that I can't both get the begin and the end of a temporary object.

I would like to implement a python-like mapping function in c++ that works on vectors of a type and maps them to another vector (of possibly another type).

This is my approach:

template <class T, class U, class UnaryOperator>
std::vector<T> map(const std::vector<T>& vectorToMap, UnaryOperator operation)
{
    std::vector<U> result;
    result.reserve(vectorToMap.size());
    std::transform(vectorToMap.begin(), vectorToMap.end(),
        std::back_inserter(result), [&operation] (U item) { return operation(item); });
    return result;
}

And this an example of how I intend to use this (where the return type of filter is the type of its first agurment):

std::vector<std::shared_ptr<Cluster>> getClustersWithLength(const std::vector<Cluster>& clusterCollection, const int& length) 
{
    return map(filter(clusterCollection, [&length] (Cluster& cluster) {
        return cluster.sizeY == length;
    }), 
    [] (const Cluster& cluster) {
        return std::make_shared<Cluster>(cluster);
    });
}

The error message I get for this code though is:

error: no matching function for call to 'map(std::vector<Cluster>,
ClusterPairFunctions::getClustersWithLength(const
std::vector<Cluster>&, const int&)::<lambda(const Cluster&)>)'

note: candidate: template<class T, class U, class UnaryOperator> std::vector<_RealType> map(const std::vector<_RealType>&, UnaryOperator)
 std::vector<T> map(const std::vector<T>& vectorToMap, UnaryOperator operation)
note:   couldn't deduce template parameter 'U'

Can you give me some help, how do I fix it? Also, can I somehow use compile-time static assertion to check if the type of operation(T t) is U?

Aucun commentaire:

Enregistrer un commentaire