Re: Optimize integer program in speed
On 17 Jun., 00:02, Keith H Duggar <dug...@alum.mit.edu> wrote:
On Jun 7, 11:09 am, Saeed Amrollahi <amrollahi.sa...@gmail.com> wrote:
[..]
given that Daniel and Alf have already explained the
reasons I will just mention that you can also work around this
issue and (usually) achieve the same performance by wrapping a
free function with a unique type viz:
bool bigger ( int i ) { return i >= D || i <= -D ; }
template < bool ( & func ) ( int i ) >
struct FuncWrap
{
bool operator ( ) ( int i ) const { return func(i) ; }
} ;
...
count += count_if(diff + 1, diff + N, FuncWrap<bigger>()) ;
The function reference is now a static argument and thus more
likely to be optimized as a direct call.
Unfortunately (AFAIK) you will need C++0x support in order to
do away with the non-type parameter explicit type declaration
(using auto and decltype).
Or just use a normal wrapper functor:
struct BiggerWrap
{
bool operator()(int i) const { return bigger(i); }
};
[..]
count += count_if(diff + 1, diff + N, BiggerWrap()) ;
The pro is, that it works independent on the language
linkage of bigger,[1] the con is, that it scales badly
because I need a separate class for each function.
In C++ we can eat the sweet part of the fruit without
the sour part, if we take advantage of lambda
expressions:
count += count_if(diff + 1, diff + N, [](int i){ return bigger(i); });
Greetings from Bremen,
Daniel Kr?gler
[1] This is especially important, if you need to wrap
a standard C library function like int abs(int), where
it is implementation-defined, whether the linkage is
extern "C" or extern "C++".
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]