我将从一个例子开始
me@blabla ./example + 3 5
Run Code Online (Sandbox Code Playgroud)
应该返回8.
我接受了参数,但我如何转换"+"
char* opp = argv[1];
Run Code Online (Sandbox Code Playgroud)
到了
+
Run Code Online (Sandbox Code Playgroud)
在我的代码中使用?
因为我想使用相当多的运算符,有没有办法在不使用大的if语句的情况下执行此操作?
我希望那清楚,谢谢!
您必须从char
操作员那里获得某种映射.假设你已经有了3
和5
在一些整数变量x
和y
,简单的解决方法是使用一个switch
语句:
switch (opp[0]) {
case '+': result = x + y; break;
case '-': result = x - y; break;
// and so on...
}
Run Code Online (Sandbox Code Playgroud)
或者,你可以有一个std::map
从char
s到std::function<int(const int&,const int&)>
:
typedef std::function<int(const int&,const int&)> ArithmeticOperator;
std::map<char, ArithmeticOperator> ops =
{{'+', std::plus<int>()},
{'-', std::minus<int>()},
// and so on...
};
int result = ops[opp[0]](x,y);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
79 次 |
最近记录: |