Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I choose the algorithm of a code only once at the beginning in C++?

Tags:

c++

There are two different algorithms being used throughout the code. Which one is chosen is determined at runtime by a parameter (e.g. true or false). I do not want to use if-statements each time the algorithm comes up.

So instead of writing the following every time

if (parameter==true)
    algorithmOne();
else
    algorithmTwo();

I want to set the algorithm at the beginning, like

if (parameter==true)
    algorithm()=algorithmOne();
else
    algorithm()=algorithmTwo();

and only use 'algorithm()' from this point forward.

How can I choose the algorithm at the beginning depending on a parameter after the code is already compiled?

Edit: How do you do that within the constructor of a class (since a pointer-to-member function is no regular pointer)? As both algorithms rely on member variables and functions of this class, it is inconvenient to derive a new class.

Solution: This could be solved with a virtual function and derived classes.

class Base
{
public:
    Base();
    virtual void algorithm() = 0;
    ~Base();
protected:
    double d;
    int i;
    ...
}

class DerivedOne : public Base
{
public:
    DerivedOne() : Noise() {};
    void algorithm() override;
    ~DerivedOne();
};

Base *b;

if (parameter==true)
    {
        b = new DerivedOne();
    }
    else
    {
        b = new DerivedTwo();
    }

Then the function can be called with:

b->algorithm();

And deleted with:

delete b;

This may not be the best way but it seems to work for me. See answers and comments.

like image 665
Oliver Avatar asked Nov 24 '25 20:11

Oliver


1 Answers

You're almost there:

auto algorithm = parameter ? algorithmOne : algorithmTwo.

No (), you're not trying to call any function here.

like image 123
MSalters Avatar answered Nov 26 '25 09:11

MSalters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!