比较c ++中的函数,简短的方法?

时间:2014-07-14 06:47:44

标签: c++

我最近一直致力于一个基本上由一个功能的24种变体组成的程序(下图)。除了我试图比较功能的部分(彼此之外),所有东西都被完美地执行。我发现可以通过编写24个if-else语句来完成,但我确信有一个更短的方法。我也尝试过载体,但现在没有运气。谢谢你的帮助!

24个功能之一:

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;

}

主要功能:

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";
  }
//...

}

1 个答案:

答案 0 :(得分:3)

这是一个干净而优雅的解决方案:

#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;
}

如果你想要存储函数的结果,你可以这样做:

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;