我的函数模板有问题。
我有3个不同的集合,并且我有这些集合的迭代器。现在我必须创建一个函数模板'apply',它将执行以下操作: 1.遍历集合的所有元素并检查predicate是否为真:
1.1if predicate返回true -那么集合的元素需要用λ'passed'进行更改
1.2If predicate return false = then集合的元素需要用λ‘’更改
请给我一个例子,我应该如何写它。
非常感谢你的帮助。更新代码如下:
#include <iostream>
#include <vector>
#include <list>
#include <functional>
using namespace std;
template<typename T>
void apply(T collBegin, T collEnd, function<bool(int)> f1, function<int(int)> f2, function<int(int)> f3)
{
for (T actualPosition = collBegin; actualPosition != collEnd; ++actualPosition) {
if (f1(*actualPosition)) {
//the argument matches the predicate function f1
*actualPosition = f2(*actualPosition);
}
else {
//the argument doesn't match the predicate function f1
*actualPosition = f3(*actualPosition);
}
}
}
int main()
{
int arr[]{ 1,2,3,4,5,6,7,8,9 };
auto predicate = [](int arg) -> bool { return arg % 2 == 0; };
auto passed = [](int arg) -> int { return arg / 2; };
auto rejected = [](int arg) -> int { return (3 * arg) + 1; };
apply(arr, arr + std::size(arr), predicate, passed, rejected);
std::vector<int> vec(arr, arr + std::size(arr));
apply(vec.begin(), vec.end(), predicate, passed, rejected);
std::list<int> lis(vec.begin(), vec.end());
apply(lis.begin(), lis.end(), predicate, passed, rejected);
for (auto e : lis) std::cout << e << " ";
std::cout << '\n';
}
这段代码可以工作。但是我想把它从int改成T,我该怎么做呢?
发布于 2018-05-28 01:00:30
Sooo代码应该是什么样子的?你能写一个例子吗?
下面的代码会编译并运行,但我不确定这是否是您想要的:
#include <iostream>
#include <vector>
#include <list>
#include <functional>
#include <algorithm>
template<typename T, typename U>
void apply(T collBegin, T collEnd, std::function<bool(U const &)> f1, std::function<U(U const &)> f2, std::function<U(U const &)> f3)
{
std::for_each(collBegin, collEnd, [&](auto &el) { el = f1(el) ? f2(el) : f3(el); });
}
int main()
{
std::function<bool(int const &)> predicate = [](int const &arg) -> bool { return arg % 2 == 0; };
std::function<int(int const &)> passed = [](int const &arg) -> int { return arg / 2; };
std::function<int(int const &)> rejected = [](int const &arg) -> int { return (3 * arg) + 1; };
int arr[]{ 1,2,3,4,5,6,7,8,9 };
apply(arr, arr + sizeof(arr)/sizeof(int), predicate, passed, rejected);
std::vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
apply(vec.begin(), vec.end(), predicate, passed, rejected);
std::list<int> lis(vec.begin(), vec.end());
apply(lis.begin(), lis.end(), predicate, passed, rejected);
for (auto e : lis) std::cout << e << " ";
std::cout << '\n';
}
1 2 16 4 4 5 34 1 7
https://stackoverflow.com/questions/50554161
复制相似问题