【发布时间】:2019-09-12 11:27:48
【问题描述】:
您好,我被要求在此示例中模拟算法 std::copy_if,将奇数复制到整数的 list 中,偶数也复制到另一个列表中,所以这是我的示例:
#include <list>
#include <vector>
#include <iostream>
template <typename T>
bool is_odd_pred(T x) {
return x % 2 != 0;
}
template <typename T>
bool is_even_pred(T x) {
return !(x % 2);
}
template <class T, class U>
void cpy_if(T first, T last, U destIt, bool(*pfnPred)(decltype(*first + 1))) {
while (first != last) {
if (pfnPred(*first))
*destIt++ = *first;
++first;
}
}
int main() {
std::vector<int> v1{ 10, 27, 57, 77, 81, 24, 16, 23, 28 };
for (auto i : v1)
std::cout << i << ", ";
std::cout << std::endl;
std::list<int> li_odd;
//cpy_if(v1.cbegin(), v1.cend(), li.begin(),
// [](decltype(*v1.cbegin() + 1) a) { return (a % 2 != 0); });
cpy_if(v1.cbegin(), v1.cend(), std::back_inserter(li_odd), is_odd_pred);
for (auto i : li_odd)
std::cout << i << ", ";
std::cout << std::endl;
std::list<int> li_even;
cpy_if(v1.cbegin(), v1.cend(), std::back_inserter(li_even), is_even_pred);
for (auto i : li_even)
std::cout << i << ", ";
std::cout << std::endl;
}
该程序看起来运行良好,但是在我的 cpy_if 算法中使用 decltype 的上下文是否正确?因为我只让算法有两种元素类型,它们被认为是迭代器。?感谢您提供任何帮助、提示和建议。
【问题讨论】:
-
为什么是
decltype(*first + 1)而不是decltype(*first)?不一样吗? -
@user31264 第二个是参考。
-
@ItachiUchiwa 收到答案后请不要对问题进行重大更改。
-
@HolyBlackCat 是的。我还没做。
-
@ItachiUchiwa 我说的是你编辑了
+ 1。 :) 我已将其重新编辑。
标签: c++ algorithm c++11 templates decltype