简体   繁体   中英

C++ analogue of mapping function

I'm surprised that I didn't find map function in standard C++ lib. Now I'm using this solution

template <typename Container, typename InputIterator, typename UnaryPredicate>
Container filter(InputIterator _from, InputIterator _to, UnaryPredicate _pred)
{
    Container collection;
    return std::accumulate(_from, _to, collection, 
        [_pred] (Container acc, const InputIterator::value_type & val) -> Container
        {
            if (_pred(val))
                acc.insert(std::end(acc), val);
            return acc;
        });
}

//////////////////////////////
// usage

    std::vector<int> vec = {0, 1, 2, 3};
    std::vector<int> newVec = filter<decltype(newVec)>(std::begin(vec), std::end(vec),
        [] (int n)
        {
            return n % 2 == 0;
        });

but maybe some more common solution exists


edit : as is said below, it's filtering function. Okay, here is my map implementation:

template <typename T, typename MapFunction>
T map(T source, MapFunction func)
{
    T collection;
    for (auto val : source)
    {
        collection.insert(std::end(collection), func(val));
    }
    return collection;
}

so problem with std::transform and others that they changes source collection, but they should return another one.

The closest to the map (builtin of python, for example) would be std::for_each or std::transform , applying a function to a range defined by an iterators pair:

Example from en.cppreference.com , for a transform in-place:

int main()
{
    std::string s("hello");
    std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
    std::cout << s;
}

Or a for_each with a lambda function, here we increment each element by 1:

int main()
{
    std::vector<int> nums{3, 4, 2, 9, 15, 267};
    std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });
}

Part of the <algorithm> header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM