Hello I am asked to simulate the algorithm std::copy_if in this example to copy the odd values into s list of integers and the even ones also int another list so here is my example:
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;
}
The program looks to work fine but Is it that correct context to use decltype in my cpy_if algorithm? Because I only made the algorithm has one element type which is considered to be an iterator.? Thank you for any help, tips, suggestion.
Aucun commentaire:
Enregistrer un commentaire