sdgaw erzswer
sdgaw erzswer

Reputation: 2382

comparing functions in c++, short way?

I've been recently working on a program which consists basically of 24 variations of one function(below). Everything gets executed perfectly apart from the part where I try to compare functions(with eachother). I found out that it is possible to be done by writing 24 if-else statements, yet I am certain there is a shorter way. I've also tried with vectors but no luck for now. Thanks for any help!

one of 24 functions:

int funk1()
{
ifstream myfile ("file.txt");
string line;
int i;

class1 obj1;

obj1.atr1= "Somename";
obj1.atr2="GAATTC";


while (getline(myfile, line))
    {

        i = countSubstring(line, obj1.atr2);
        obj1.sum += i;
    };
    cout<<obj1.sum<<": "<<obj1.atr1<<"\n";
    return obj1.sum;

}

The main function:

int main(){





 funk1();
 funk2();
 funk3();
 funk4();
 funk5();
 funk6();
 funk7();
 funk8();
 funk9();
 funk10();
 funk11();
 funk12();
 funk13();
 funk14();
 funk15();
 funk16();
 funk17();
 funk18();
 funk19();
 funk20();
 funk21();
 funk22();
 funk23();
 funk24();

//This is one way to do it

  if (funk18() > funk1())
  {
      cout<<funk18<<" is the biggest";
  }
//...

}

Upvotes: 0

Views: 105

Answers (1)

bolov
bolov

Reputation: 75698

Here is a clean and elegant solution:

#include <iostream>
#include <functional>
#include <vector>
#include <limits>
#include <algorithm>

using namespace std;

using MyFunc = std::function<int()>;

int f1() { return 1; }
int f2() { return 15;}
int f3() { return 3; }

int main() {
    std::vector<MyFunc> my_functions = {f1, f2, f3};
    int max = std::numeric_limits<int>::min();

    for (auto const &f : my_functions) {
        max = std::max(max, f());
    }

    cout << max << endl;
    return 0;
}

if you want to store the results from functions instead, you could do:

std::vector<int> my_results;
my_results.reserve(my_functions.size());

for (auto const &f : my_functions) {
    my_results.push_back(f());
}
auto max_it = std::max_element(std::begin(my_results), std::end(my_results));
cout << *max_it << endl;

Upvotes: 3

Related Questions