gpt4 book ai didi

映射函数的 C++ 模拟

转载 作者:行者123 更新时间:2023-11-28 02:45:00 28 4
gpt4 key购买 nike

令我惊讶的是,我没有在标准 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;
});

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


编辑:如下所述,它是过滤功能。好的,这是我的 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 和其他人有问题,他们改变了源集合,但他们应该返回另一个。

最佳答案

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

或者一个for_each使用 lambda 函数,这里我们将每个元素递增 1:

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

<algorithm> 的一部分标题。

关于映射函数的 C++ 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24718051/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com