【问题标题】:C++ analogue of mapping function映射函数的 C++ 类似物
【发布时间】:2014-09-03 06:41:08
【问题描述】:

我很惊讶在标准 C++ 库中没有找到 map 函数。现在我正在使用这个解决方案

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;
        });

但也许还有一些常见的解决方案存在


edit :如下所述,它是过滤功能。好的,这是我的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;
}

std::transform 和其他人的问题是他们更改了源集合,但他们应该返回另一个。

【问题讨论】:

  • 为什么在展示filter 的实现的同时询问map 函数?
  • C++ 有std::for_each 在每个元素上调用一个函数。
  • @juanchopanza 过滤器只是带有谓词的映射。误会了,对我来说它们几乎是一样的
  • 不,过滤器接受很多东西,但返回的东西更少。 Map 将操作应用于 N 个事物,为您提供 N 个结果。
  • 你说得对,但在 FP 中你不会记住诸如集合大小之类的事情。

标签: c++ vector functional-programming standards standard-library


【解决方案1】:

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

来自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;
}

或者带有 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++; });
}

&lt;algorithm&gt; 标头的一部分。

【讨论】:

  • 请注意,如果使用toupper,则应确保其参数是unsigned char(或至少在一个范围内)。 “你好”除非是一些晦涩难懂的字符集(如果允许的话),但一般来说这是行不通的。
  • @chris:无论如何,toupper 不适合大多数语言环境。
猜你喜欢
  • 2012-06-17
  • 1970-01-01
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 2023-01-29
  • 2020-05-16
相关资源
最近更新 更多