利用function跟map来取代if else 效率也会比好
#include <iostream>
#include <map>
#include <functional>
using namespace std;
int fun1(int a,int b){ return a + b;}
int fun2(int a,int b){ return a - b;}
int fun3(int a,int b){ return a * b;}
int fun4(int a,int b){ return a / b;}
int main() {
map<int,function<int(int,int)>> m_fun;
m_fun.insert(make_pair(1,fun1));
m_fun.insert(make_pair(2,fun2));
m_fun.insert(make_pair(3,fun3));
m_fun.insert(make_pair(4,fun4));
int a[4] = {1,2,3,4};
for(auto x : a)
{
cout<<m_fun[x](6,3)<<endl;
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
网友评论