how to pass a templated function as argument?
Nov 19, 2018 at 9:38pm UTC
I'm playing a bit around with function pointers. Here I tried to implement a simple generic sorting algorithm where a function should been passed for evaluating the the comparison. But I couldn't get it to work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <iostream>
#include <list>
template <typename T>
bool (*fct)(T a, T b);
template <typename Itr, typename T>
void sort( Itr begin, Itr end, fct<T> cmp ) // here I need help
{
for ( auto i = begin; i != end; ++i)
{
for ( auto k = i; k != end; ++k)
{
if ( cmp(*k,*i) ) continue ;
auto tmp = *k;
*k = *i;
*i = tmp;
}
}
}
int main()
{
std::list<int > l = { 1, 3 , 6, 2, 0};
sort( l.begin(), l.end(), [](int a,int b)->bool {return a<b;} );
for ( auto item : l) std::cout << item;
}
Thanks for help.
Nov 19, 2018 at 9:55pm UTC
It's simpler than you have it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
#include <list>
template <typename Itr, typename Cmp>
void sort(Itr begin, Itr end, Cmp cmp)
{
for (auto i = begin; i != end; ++i)
for (auto j = i; j != end; ++j)
if (!cmp(*j, *i))
std::swap(*j, *i);
}
int main()
{
std::list<int > l = { 1, 3 , 6, 2, 0};
sort(l.begin(), l.end(), [](int a,int b)->bool {return a<b;} );
for (auto item : l) std::cout << item;
}
Last edited on Nov 19, 2018 at 9:57pm UTC
Topic archived. No new replies allowed.