有没有办法在'if'条件下用>替换字符串">"?

NDe*_*iny 2 c++

我遇到了以下用例,但我找不到合适的解决方案.有没有办法用条件来代替字符串"<"或">" <>if条件?

例:

  string condition = "<";
  if (10 condition 8)   // Here I want to replace condition with <
  {
      // Some code
  }
Run Code Online (Sandbox Code Playgroud)

我不想这样做:

if ("<" == condition)
{
   if (10 < 8)
   {
   }
}
else if (">" == condition)
{
   if (10 > 10)
   {
   }
}
Run Code Online (Sandbox Code Playgroud)

而且我的病情会在运行期间发生变化.如果存在于上面,我只是在寻找一种简单的方法.

使用案例:用户将提供如下查询:

input: 10 > 9   =>  output: true
input: 10 < 7   =>  output: false
Run Code Online (Sandbox Code Playgroud)

基本上我需要解析这个查询,因为我将这3个单词(10,>,9)作为字符串,并且我想以某种方式将字符串">"或"<"转换为实际符号><.

Che*_*Alf 5

您可以将字符串映射到标准库比较器仿函数,例如std::less通过a std::map或a std::unordered_map.

  • @RobertColumbia:对不起,我不明白你是如何得出结论的.没有涉及预处理器. (4认同)
  • 预处理器不需要用于此. (3认同)

Col*_*ica 5

你不能用C++创建一个新的运算符(我可以用C++ 创建一个新的运算符吗?).我可以看到你从这个想法来自哪里,但语言不支持这一点.但是,您可以创建一个函数,该函数接受两个操作数和一个字符串"argument"并返回适当的值.

bool CustomCompare(int operand1, int operand2, string op)
{
    if (op == "<")
    {
        return operand1<operand2;
    }
    if (op == ">")
    {
        return operand1>operand2;
    }
    if (op == "_")
    {
        return DoTheHokeyPokeyAndTurnTheOperandsAround(operand1, operand2);
    }
}
Run Code Online (Sandbox Code Playgroud)