How to put min and max inside a function - c++

I'd like to do this piece of code
auto f = player == color ? max : min;
Where player and color are booleans and min and max are standard functions from C++ library.
But I get this error : error: overloaded function with no contextual type information
How do I tell the compiler I want to load min and max that compares integers?
Here's how to reproduce the error :
1) create a file toto.cpp
2) paste this :
int main() {
bool one = 1;
bool zero = 0;
auto f = one == zero ? std::min : std::max;
return 0;
}
3) compile it g++ toto.cpp
4) run it ./a.out
5) observe the same error as above

Something like this?
#include <algorithm>
int main()
{
auto Max = [](int a, int b){return std::max(a, b);};
auto Min = [](int a, int b){return std::min(a, b);};
bool one = 1;
bool zero = 0;
auto f = one == zero ? Min : Max;
return 0;
}
I think the compiler is simply not able to deduce the template parameter(s) for std::max and std::min when you write it like:
auto f = one == zero ? std::min : std::max;

Related

Absolute hysteresis calculation in C++

I want to implement a template function, which detects if the difference of ValueA and ValueB is bigger than a given hystersis.
e.x.
ValueA=5, ValueB=7, Hystersis=1 -> true
ValueA=5, ValueB=7, Hystersis=3 -> false
ValueA=-5, ValueB=1, Hystersis=7 -> false
So I implemented this function:
template<typename T>
bool MyClass::IsHysteresisExceeded(T ValueA, T ValueB, T Hysteresis) {
T ValueMax = std::max(ValueA, ValueB);
T ValueMin = std::min(ValueA, ValueB);
return (ValueMax - ValueMin) > Hysteresis;
}
But with the following parameters this function returns false when I expected true as result.
IsHysteresisExceeded<int>(-2147483648, 2147483647, 10)
I know that a integer overflow occurs while subtracting, but I did not find an elegant solution yet.
I have the following solution for integers:
template<typename T>
bool IsHysteresisExceeded(T ValueA, T ValueB, T Hysteresis) {
T ValueMax = std::max(ValueA, ValueB);
T ValueMin = std::min(ValueA, ValueB);
assert(Hysteresis >= 0);
T underflowRange = std::numeric_limits<T>::min() + Hysteresis;
bool underflow = underflowRange > ValueMax;
return !underflow && (ValueMax - Hysteresis > ValueMin);
}
The trick is to detect the underflow. If it happens you may be sure ValueMin is in range <ValueMax,std::numeric_limits<T>::min()> and
(ValueMax - Hysteresis) < std::numeric_limits<T>::min() <= ValueMin
I posted the code on godbolt.org
Edit:
My previous answer used a very popular approach and was also wrong. I proposed to detect the underflow like:
T lowBound = ValueMax - Hysteresis;
bool underflow = lowBound > ValueMax;
Although it produces expected results on the architectures i know, it is an undefined behavior.
One way to detect possible overflow is to use some indicator of "how far" from limits is a value. I use a simple division, which wants to normalize vale values in the range [-1,1].
Then I substract both "positions" to get the range between them, and compare it with a valid range, this is, 1:
#include <limits>
#include <math.h>
#include <iostream>
template<typename T>
bool IsHysteresisExceeded(T ValueA, T ValueB, T Hysteresis) {
long double posA = (long double) ValueA / std::numeric_limits<T>::max();
long double posB = (long double) ValueB / std::numeric_limits<T>::max();
if (std::fabs(posA - posB) > 1)
return true; //ValueMax - ValueMin would overflow
T ValueMax = std::max(ValueA, ValueB);
T ValueMin = std::min(ValueA, ValueB);
return (ValueMax - ValueMin) > Hysteresis;
}
int main()
{
std::cout << (IsHysteresisExceeded<int>(-2147483648, 2147483647, 10) ? "Exceeded" : "In range") << std::endl;
}
I was hoping that this version would compile down efficiently, but alas, the C++ compiler on my machine is unable to merge the two branches. Posting anyway because it uses only +, -, < and a default constructor for 0.
#include <algorithm>
#include <tuple>
template <typename T> bool IsHysteresisExceeded(T a, T b, T h) {
std::tie(a, b) = std::minmax(a, b);
return a < T{} ? h + a < b : h < b - a;
}
bool test(int a, int b, int h) { return IsHysteresisExceeded(a, b, h); }

Computing fibonacci in c++ function and throwing compile-time error

I need to write this function fibo.
If the number is too big it should be shown as compile error (the last line of main function)
The main function should stay like it is.
Any suggestions?
#include <iostream>
int fibo(int n)
{
if (n <= 1)
return n;
//if (n>=300) throws ... ?
return fibo(n - 1) + fibo(n - 2);
}
int main()
{
static_assert(fibo(7) == 34);
const int k = fibo(9);
std::cout << k << std::endl;
const int l = fibo(300); // 300th Fibonacci number is large for int
}
You can make fibo a constexpr function, and then throw if the argument is invalid. The throw in a constexpr function will lead to a compile time error if fibo is evaluated at compile time, and a run time error otherwise:
constexpr int fibo(int n)
{
if (n >= 300) throw;
if (n <= 1) return n;
return fibo(n-1) + fibo(n-2);
}
and you can use it like this:
int j = fibo(300); // run time error
constexpr int k = fibo(300); // compile time error
Here's a demo.
Note that you can't static_assert inside the definition of fibo since the condition depends on the function argument, which is not a constant expression.

Pass a function as argument, without knowlegde of number of arguments of this function [duplicate]

long time browser, first time asker here. I've written a number of scripts for doing various 1D numerical integration methods and compiled them into a library. I would like that library to be as flexible as possible regarding what it is capable of integrating.
Here I include an example: a very simple trapezoidal rule example where I pass a pointer to the function to be integrated.
// Numerically integrate (*f) from a to b
// using the trapezoidal rule.
double trap(double (*f)(double), double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += (*f)(xi); }
else { s += 2*(*f)(xi); }
}
s *= (b-a)/(2*N);
return s;
}
This works great for simple functions that only take one argument. Example:
double a = trap(sin,0,1);
However, sometimes I may want to integrate something that has more parameters, like a quadratic polynomial. In this example, the coefficients would be defined by the user before the integration. Example code:
// arbitrary quadratic polynomial
double quad(double A, double B, double C, double x) {
return (A*pow(x,2) + B*x + C);
}
Ideally, I would be able to do something like this to integrate it:
double b = trap(quad(1,2,3),0,1);
But clearly that doesn't work. I have gotten around this problem by defining a class that has the coefficients as members and the function of interest as a member function:
class Model {
double A,B,C;
public:
Model() { A = 0; B = 0; C = 0; }
Model(double x, double y, double z) { A = x; B = y; C = z; }
double func(double x) { return (A*pow(x,2)+B*x+C); }
};
However, then my integration function needs to change to take an object as input instead of a function pointer:
// Numerically integrate model.func from a to b
// using the trapezoidal rule.
double trap(Model poly, double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += poly.func(xi); }
else { s += 2*poly.func(xi); }
}
s *= (b-a)/(2*N);
return s;
}
This works fine, but the resulting library is not very independent, since it needs the class Model to be defined somewhere. Also, ideally the Model should be able to change from user-to-user so I wouldn't want to fix it in a header file. I have tried to use function templates and functors to get this to work but it is not very independent since again, the template should be defined in a header file (unless you want to explicitly instantiate, which I don't).
So, to sum up: is there any way I can get my integration functions to accept arbitrary 1D functions with a variable number of input parameters while still remaining independent enough that they can be compiled into a stand-alone library? Thanks in advance for the suggestions.
What you need is templates and std::bind() (or its boost::bind() counterpart if you can't afford C++11). For instance, this is what your trap() function would become:
template<typename F>
double trap(F&& f, double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += f(xi); }
// ^
else { s += 2* f(xi); }
// ^
}
s *= (b-a)/(2*N);
return s;
}
Notice, that we are generalizing from function pointers and allow any type of callable objects (including a C++11 lambda, for instance) to be passed in. Therefore, the syntax for invoking the user-provided function is not *f(param) (which only works for function pointers), but just f(param).
Concerning the flexibility, let's consider two hardcoded functions (and pretend them to be meaningful):
double foo(double x)
{
return x * 2;
}
double bar(double x, double y, double z, double t)
{
return x + y * (z - t);
}
You can now provide both the first function directly in input to trap(), or the result of binding the last three arguments of the second function to some particular value (you have free choice on which arguments to bind):
#include <functional>
int main()
{
trap(foo, 0, 42);
trap(std::bind(bar, std::placeholders::_1, 42, 1729, 0), 0, 42);
}
Of course, you can get even more flexibility with lambdas:
#include <functional>
#include <iostream>
int main()
{
trap(foo, 0, 42);
trap(std::bind(bar, std::placeholders::_1, 42, 1729, 0), 0, 42);
int x = 1729; // Or the result of some computation...
int y = 42; // Or some particular state information...
trap([&] (double d) -> double
{
x += 42 * d; // Or some meaningful computation...
y = 1; // Or some meaningful operation...
return x;
}, 0, 42);
std::cout << y; // Prints 1
}
And you can also pass your own stateful functors tp trap(), or some callable objects wrapped in an std::function object (or boost::function if you can't afford C++11). The choice is pretty wide.
Here is a live example.
What you trying to do is to make this possible
trap( quad, 1, 2, 3, 0, 1 );
With C++11 we have alias template and variadic template
template< typename... Ts >
using custom_function_t = double (*f) ( double, Ts... );
above define a custom_function_t that take a double and variable numbers of arguments.
so your trap function becomes
template< typename... Ts >
double trap( custom_function_t<Ts...> f, Ts... args, double a, double b ) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += f(xi, args...); }
else { s += 2*f(xi, args...); }
}
s *= (b-a)/(2*N);
return s;
}
Usage:
double foo ( double X ) {
return X;
}
double quad( double X, double A, double B, double C ) {
return(A*pow(x,2) + B*x + C);
}
int main() {
double result_foo = trap( foo, 0, 1 );
double result_quad = trap( quad, 1, 2, 3, 0, 1 ); // 1, 2, 3 == A, B, C respectively
}
Tested on Apple LLVM 4.2 compiler.

C++: pass function with arbitrary number of parameters as a parameter

long time browser, first time asker here. I've written a number of scripts for doing various 1D numerical integration methods and compiled them into a library. I would like that library to be as flexible as possible regarding what it is capable of integrating.
Here I include an example: a very simple trapezoidal rule example where I pass a pointer to the function to be integrated.
// Numerically integrate (*f) from a to b
// using the trapezoidal rule.
double trap(double (*f)(double), double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += (*f)(xi); }
else { s += 2*(*f)(xi); }
}
s *= (b-a)/(2*N);
return s;
}
This works great for simple functions that only take one argument. Example:
double a = trap(sin,0,1);
However, sometimes I may want to integrate something that has more parameters, like a quadratic polynomial. In this example, the coefficients would be defined by the user before the integration. Example code:
// arbitrary quadratic polynomial
double quad(double A, double B, double C, double x) {
return (A*pow(x,2) + B*x + C);
}
Ideally, I would be able to do something like this to integrate it:
double b = trap(quad(1,2,3),0,1);
But clearly that doesn't work. I have gotten around this problem by defining a class that has the coefficients as members and the function of interest as a member function:
class Model {
double A,B,C;
public:
Model() { A = 0; B = 0; C = 0; }
Model(double x, double y, double z) { A = x; B = y; C = z; }
double func(double x) { return (A*pow(x,2)+B*x+C); }
};
However, then my integration function needs to change to take an object as input instead of a function pointer:
// Numerically integrate model.func from a to b
// using the trapezoidal rule.
double trap(Model poly, double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += poly.func(xi); }
else { s += 2*poly.func(xi); }
}
s *= (b-a)/(2*N);
return s;
}
This works fine, but the resulting library is not very independent, since it needs the class Model to be defined somewhere. Also, ideally the Model should be able to change from user-to-user so I wouldn't want to fix it in a header file. I have tried to use function templates and functors to get this to work but it is not very independent since again, the template should be defined in a header file (unless you want to explicitly instantiate, which I don't).
So, to sum up: is there any way I can get my integration functions to accept arbitrary 1D functions with a variable number of input parameters while still remaining independent enough that they can be compiled into a stand-alone library? Thanks in advance for the suggestions.
What you need is templates and std::bind() (or its boost::bind() counterpart if you can't afford C++11). For instance, this is what your trap() function would become:
template<typename F>
double trap(F&& f, double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += f(xi); }
// ^
else { s += 2* f(xi); }
// ^
}
s *= (b-a)/(2*N);
return s;
}
Notice, that we are generalizing from function pointers and allow any type of callable objects (including a C++11 lambda, for instance) to be passed in. Therefore, the syntax for invoking the user-provided function is not *f(param) (which only works for function pointers), but just f(param).
Concerning the flexibility, let's consider two hardcoded functions (and pretend them to be meaningful):
double foo(double x)
{
return x * 2;
}
double bar(double x, double y, double z, double t)
{
return x + y * (z - t);
}
You can now provide both the first function directly in input to trap(), or the result of binding the last three arguments of the second function to some particular value (you have free choice on which arguments to bind):
#include <functional>
int main()
{
trap(foo, 0, 42);
trap(std::bind(bar, std::placeholders::_1, 42, 1729, 0), 0, 42);
}
Of course, you can get even more flexibility with lambdas:
#include <functional>
#include <iostream>
int main()
{
trap(foo, 0, 42);
trap(std::bind(bar, std::placeholders::_1, 42, 1729, 0), 0, 42);
int x = 1729; // Or the result of some computation...
int y = 42; // Or some particular state information...
trap([&] (double d) -> double
{
x += 42 * d; // Or some meaningful computation...
y = 1; // Or some meaningful operation...
return x;
}, 0, 42);
std::cout << y; // Prints 1
}
And you can also pass your own stateful functors tp trap(), or some callable objects wrapped in an std::function object (or boost::function if you can't afford C++11). The choice is pretty wide.
Here is a live example.
What you trying to do is to make this possible
trap( quad, 1, 2, 3, 0, 1 );
With C++11 we have alias template and variadic template
template< typename... Ts >
using custom_function_t = double (*f) ( double, Ts... );
above define a custom_function_t that take a double and variable numbers of arguments.
so your trap function becomes
template< typename... Ts >
double trap( custom_function_t<Ts...> f, Ts... args, double a, double b ) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += f(xi, args...); }
else { s += 2*f(xi, args...); }
}
s *= (b-a)/(2*N);
return s;
}
Usage:
double foo ( double X ) {
return X;
}
double quad( double X, double A, double B, double C ) {
return(A*pow(x,2) + B*x + C);
}
int main() {
double result_foo = trap( foo, 0, 1 );
double result_quad = trap( quad, 1, 2, 3, 0, 1 ); // 1, 2, 3 == A, B, C respectively
}
Tested on Apple LLVM 4.2 compiler.

Compare 4 variables to find the lowest C++

I want to find the lowest number of the four, but this looks kinda wierd , isnt there a smarter and shorter way to do it?
That is what I have:
int findlowest(int one, int two, int three, int four) {
int output = one //as of now , we will be outputting one , except if we find a lower score.
if(output > two) { out = two;} // if output is proven to be bigger than two, two is our new output.
if(output > three){ output = three;} //same operation with three
if(output > four){ output = four;} // same operation with four
return output;
}
std::min(a, std::min(b, std::min(c, d)));
Include <algorithm>.
c++11:
int minimum = std::min( { 1,2,3,4,5 } );
min_int = min(min(one, two), min(three, four));
int a[] = {1,2,3,4,5};
int minimum = *std::min_element(a, a+5);
Lots of answers saying to use the Standard library facilities - they're right, it covers this case! But, for the educational value, here's a slightly more concise way to do what you were doing:
int findlowest(int a, int b, int c, int d)
{
int of_a_b = a < b ? a : b;
int of_c_d = c < d ? c : d;
return of_a_b < of_c_d ? of_a_b : of_c_d;
}
Easily generalised for different types (though C++03 doesn't make it easy to generalise for arbitrary numbers of arguments):
template <typename T>
T findlowest(const T& a, const T& b, const T& c, const T& d)
{
const T& of_a_b = a < b ? a : b;
const T& of_c_d = c < d ? c : d;
return of_a_b < of_c_d ? of_a_b : of_c_d;
}