简体   繁体   English

映射函数的C ++模拟

[英]C++ analogue of mapping function

I'm surprised that I didn't find map function in standard C++ lib. 令我感到惊讶的是,我没有在标准C ++库中找到map函数。 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: 好的,这是我的map实现:

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. 所以std::transform和其他问题出现了,他们改变了源集合,但是他们应该返回另一个。

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: 最接近map (例如python内置)的是std::for_eachstd::transform ,将函数应用于由迭代器对定义的范围:

Example from en.cppreference.com , for a transform in-place: 来自en.cppreference.com的示例,用于就地转换:

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: 或带有lambda函数的for_each ,在这里我们将每个元素加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. <algorithm>标头的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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