Making an array of function pointers [duplicate] - c++

This question already has answers here:
How define an array of function pointers in C
(5 answers)
Closed 4 years ago.
My problem is: I want to write a program which create an array function pointers. I know how to make pointer to function, but don't know how to make array of them.
This is what I tried up to now:
double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
double mult(double a, double b) { return a * b; }
double div(double a, double b) { return a/b; }
int main() {
double(*Padd)(double a, double b);
double(*Psub)(double a, double b);
double(*Pmult)(double a, double b);
double(*Pdiv)(double a, double b);
Padd = &add;
Psub = ⊂
Pmult = &mult;
Pdiv = ÷
}
In my code I create these pointers to functions in an array like e.g.
double Tpointers[3];
Tpointers[0] = Padd;
Tpointers[1] = Psub;
Tpointers[2] = Pmult;
Tpointers[3] = Pdiv;
How do I do this?

Simply declare a new type 'Tpointers' that represent a pointer to a function that give two double and return a double.
And in the code you can create an array of functions.
#include<iostream>
// The function pointer type!
typedef double (*Tpointers)(double, double);
double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
double mult(double a, double b) { return a * b; }
double div(double a, double b) { return a / b; }
int main() {
// A functions pointers array .
Tpointers fun_array[4];
// Assign the values
fun_array[0] = &add;
fun_array[1] = ⊂
fun_array[2] = &mult;
fun_array[3] = &div;
// A little test
std::cout << fun_array[2](3, 3) << " " << fun_array[3](3,3) << " " << fun_array[1](3,3)
<< std::endl;
return 0;
}
In c++ you can also create an std::vector of functions pointer ... or any containers from the std libraries of "Tpointers".

Related

how do i return multiple values from a function in c++ [duplicate]

This question already has answers here:
Returning multiple values from a C++ function
(23 answers)
Closed 1 year ago.
I want to return two float variables from a bool function althought i dont know how to do it. What should i write in main? Here is my code.
bool triwnymo(int a, int b, int c, float& x1, float& x2){
int d;
d=diak(a,b,c);
if(d>0){
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
return x1,x2;
return true;
}else if(d==0){
x1=-b/(2*a);
x2=x1;
return x1,x2;
return true;
}else{
return false;
}
}
You can use a custom data structure to return as many values you like:
struct triwnymo_result_type {
float root1 = 0.0;
float root2 = 0.0;
bool has_solution = false;
};
triwnymo_result_type triwnymo(int a, int b, int c){
int d = diak(a,b,c);
if(d>0) {
return {(-b+sqrt(d))/(2*a), (-b-sqrt(d))/(2*a), true};
} else if(d==0) {
int x=-b/(2*a);
return {x,x,true};
} else {
return {0.0,0.0,false};
}
}
Note that return x1,x2; is using the comma operator. The comma operator evaluates both operands, discards the first and results in the value of the latter. Thats not what you want. Also return true; after you already returned from the function is never reached. You can only return from a function once.
I didn't want to change too much, but you don't really need to distinguish between d>0 and d==0 because when d==0 then -b+sqrt(d) == -b-sqrt(d) == -b.
#include <tuple>
// bad answer.
//// by pair
//std::pair<bool, float> triwnymo(...) {...}
// 1. by tuple
std::tuple<bool, float, float> triwnymo(...) {...}
// 2. by class or struct
struct data { bool b; float f1; float f2; };
data triwnymo(...) {...}
// 3. by reference or pointer
bool triwnymo(..., float& float_out1, float& float_out2) {...}
// other way
float f1, f2;
bool triwnymo(...) {...; f1 = ?; f2 = ?; }

c++ return two arrays from the function

I find a solution to the equation using the bisection method.
And I need to find the value of a and b on some iterations. Therefore, I made two arrays for these points, respectively.
in order to "pull out" the number of iterations from the function, I had no problems. They are displayed on the screen. But how do I "pull out" these two arrays?Please tell me how to do it. Thank you in advance!
double f1(double x){
return x*x-5*sin(x);
}
double f2(double x){
return exp(x)-pow(10,x);
}
double f3(double x){
return sin(x)-x+0.15;
}
double f4(double x){
return x-pow(9+x,0.5)+x*x-4;
}
double dihotom (double a , double b , double e , double(*fp)(double),int &iter,double &points_a[],double &points_b[]){
double c , fc , fa = fp(a);
iter=(log10((b-a)/e))/log10(2);
int step = iter/3;
int step_current = step;
int it=0;
int k=0;
do{
c=(a+b)/2;
fc=fp(c);
if (fa*fc<=0) b = c ; else a = c;
it++;
if(it==step_current){
points_a[k]=a;
points_b[k]=b;
k++;
step_current=step_current+step;
}
fa=fp(a);
printf ("it %d: a = %lf,b = %lf\n",iter,a,b);
}while (fabs(a-b)>=e);
return c;
}
int main(int argc, char *argv[]) {
int int_s=0;
double points_a[3];
double points_b[3];
double k3= dihotom (0.5,1,0.0001,f3,int_s,points_a[3],points_b[3]);
printf("For F3 - root = %lf, F3(%.2lf)=%lf ;iter =%d\n", k3, k3 ,f3(k3),int_s);
int i=0;
for(i=0;i<3;i++){
printf("step : %d , a: %lf, b: %lf ", i,points_a[i],points_b[i]);
}
return 0;
}
In your case, you should take the arrays by reference:
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double (&points_a)[3], double (&points_b)[3]) {
// ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
You could also let the arrays decay into pointers:
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double points_a[], double points_b[]) {
or
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double* points_a, double* points_b) {
But by taking them by reference, you make sure that you only accept arrays of the correct size.
In either case, the call to the function will simply be:
double k3 = dihotom(0.5, 1, 0.0001, f3, int_s, points_a, points_b);
Demo
If you want to return two arrays from a function then make a struct with two vectors. Something like this. The way you are doing it is harder to maintain, who will allocate the arrays and delete them for example?
// todo for you : create better names then points_a and points_b
struct my_result_t
{
std::vector<double> points_a;
std::vector<double> points_b;
};
my_result_t function();
{
my_result_t result;
result.points_a.push_back(1.0);
result.points_b.push_back(2.0);
return result;
}
int main()
{
auto result = function();
std::cout << result.points_a[0];
}

Different arguments to pure virtual functions c++

I am working on an assignment about pure virtual functions. I have two different classes that i wish to use a pure virtual function. The virtual function is used to calculate area, each class i.e ( square, triangle) use different arguments to calculate the area. How can i make both getArea functions work with the pure virtual function?
#include <iostream>
#include <cmath>
using namespace std;
class Point{
public:
double x, y;
Point(double a = 0, double b = 0){x = a; y = b;}
Point operator + (Point const &obj){
Point p;
p.x = x + obj.x;
p.y = y + obj.y;
return p;
}
Point operator - (Point const &obj){
Point p;
p.x = x - obj.x;
p.y = y - obj.y;
return p;
}
friend ostream& operator<<(ostream& os, const Point& pt);
};
class Shape{
public:
virtual double getArea(Point a, Point b, Point c, Point d) = 0 ; // this is where i have a problem
// need this to be virtual void getArea() = 0; so i can use it for every other class but not sure how
};
class Square: public Shape{
public:
// find area from four points
double length(Point a, Point b){
double hDis = pow((b.x - a.x),2);
double vDis = pow((b.y - a.y),2);
return sqrt(hDis + vDis);
}
double area_triangle(Point a, Point b, Point c){
double A = length(a, b);
double B = length (b, c);
double C = length(a, c);
double S = (length(a, b) + length (b, c) + length(a, c))/2;
double area = sqrt((S*(S-A)*(S-B)*(S-C)));
return area;
}
double getArea(Point a, Point b, Point c, Point d){ // have to calculate area with the point coordinates
double area_tri1 = area_triangle(a, b, c);
double area_tri2 = area_triangle(a, d, c);
double total_area = area_tri1 + area_tri2;
return total_area;
}
};
class Triangle: public Shape{
public:
double length(Point a, Point b){
double hDis = pow((b.x - a.x),2);
double vDis = pow((b.y - a.y),2);
return sqrt(hDis + vDis);
}
double getArea(Point a, Point b, Point c){
double A = length(a, b);
double B = length (b, c);
double C = length(a, c);
double S = (length(a, b) + length (b, c) + length(a, c))/2;
double air = sqrt((S*(S-A)*(S-B)*(S-C)));
return air;
}
};
ostream& operator<<(ostream& os, const Point& pt)
{
os << pt.x << ", " << pt.y <<endl;
return os;
}
int main(){
Point p1(5,-5), p2(-10,7), p3(4, 23), p4(-6, 12);
Square s;
cout << s.getArea(p1, p2, p3, p4);
//! Triangle t;
//! cout << t.getArea(p1, p2,p3);
// this gives me an error because the abstract function want
// (Point a, Point b, Point c, Point d)
// how do i make this work?
}
You've designed your classes a bit strangely.
They should have data members ("member variables") that define their extents (as many Points as you need for that particular type).
Then there is no need to pass any arguments into getArea(): the implementation of this function in each class will use the member variables!
And then you won't have your problem any more, because all of the getArea() functions will have the same number of arguments: none.
If you move things out of function arguments, and into member variables, so that your classes actually contain some state, you should find that the rest of your design falls into place around that change.

Set method in a simple c++ class file returning strange values

I am having trouble using a set function in a class file. So far I have the following. I am trying to write a quadratic class that has three private data members and can calculate both the value of a quadratic and the number of real roots in the quadratic. I'm not stuck on the math part as much as I am getting the set methods to not give me weird values. When I test using main, the values for a, b, and c are numbers that I didn't input when I created the object.
Quadratic.hpp
#ifndef QUADRATIC_HPP
#define QUADRATIC_HPP
class Quadratic
{
private:
double a;
double b;
double c;
public:
Quadratic();
Quadratic(double, double, double);
void setA(double);
void setB(double);
void setC(double);
double getA();
double getB();
double getC();
double valueFor(double);
int numRealRoots();
};
#endif
Quadratic.cpp
#include <cmath>
#include <iostream>
Quadratic::Quadratic()
{
setA(1.0);
setB(1.0);
setC(1.0);
}
Quadratic::Quadratic(double A, double B, double C)
{
a = A;
b = B;
c = C;
}
void Quadratic::setA(double A)
{
a = A;
}
void Quadratic::setB(double B)
{
a = B;
}
void Quadratic::setC(double C)
{
c = C;
}
double Quadratic::getA()
{
return a;
}
double Quadratic::getB()
{
return b;
}
double Quadratic::getC()
{
return c;
}
double Quadratic::valueFor(double x)
{
return (a*(pow(x,2)) + b*x + c);
}
int Quadratic:: numRealRoots()
{
double discriminant = pow(b,2) - (4*a*c);
double epsilon = 0.00001;
int realRoots;
if (discriminant <= epsilon && discriminant > 0)
realRoots = 1;
else if (discriminant > epsilon)
realRoots = 2;
else
realRoots = 0;
return realRoots;
}
Your setB method is wrong - it updates a instead of b:
void Quadratic::setB(double B)
{
b = B; // Was "a = B;" in the original code
}

Error when using a function as an argument of a function

I'm trying to create a program to numerically integrate a function between two limits. I've created a minimal example (where the "integral" is always 1.0) to illustrate an error I get. The code below tries to use a function whose arguments are two doubles and a function from doubles to doubles:
#include <iostream>
#include <math.h>
double cons(double a, double b, double c(double d))
{
return 1.0;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f(x));
std::cout << I << "";
}
This results in an error on cpp.sh:
14:31: error: cannot convert 'double' to 'double ()(double)' for argument '3' to 'double cons(double, double, double ()(double))'
Obviously, the difference between doubles and double-valued functions is causing a problem here. How can I get this working?
You need to pass the function, not call it.
#include <iostream>
#include <math.h>
double cons(double a, double b, double c(double d))
{
return 1.0;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f);
std::cout << I << "";
}
You didn't pass a function but the result of a function, a double. Second, you didn't correctly declared a function pointer as argument.
If you want to pass a double then declare a double as argument:
double cons(double a, double b, double c)
{
return 1.0*a*b*c;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f(x));
std::cout << I << "";
}
If you want to pass a function (aka function pointer as C++ is not a functional language):
double cons(double a, double b, double (*c)(double d))
{
return 1.0*c(a);
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f);
std::cout << I << "";
}
Your problem in this case is that you are calling the function with:
double I = cons(0, 1, f(x));
so you actually give cons the return value of f() instead of the actual function. So you need to write this insteed:
double I = cons(0, 1, f);
As an alternativ you could also use lambda expressions for your problem. For example something like this:
#include <iostream>
#include <math.h>
#include <functional>
double cons(double a, double b, const std::function<double(double)>& callback)
{
// do something
}
int main()
{
double x;
double I = cons(0, 1, [](double x){ return x*x});
std::cout << I << "";
}