Comparison operator

This may be a dumb question. Is there a way to provide a runtime comparison operator using a string variable.
Suppose I have salary data in a vector.


vector < int > salary;
Input:
salary[i] != /* ==,>,<,>=,<= (any comparison operator)) */ 9000.

Login above. I save the comparison operator in the str string. str = (any comparison operator). Is there any way to check this without if and switch.


salary str 9000
+3
source share
8 answers

You can create a map with operator lines as keys and function objects for the corresponding comparison operations as values.


Map Creation:

std::map<std::string, boost::function<bool(int, int)> > ops;
ops["=="] = std::equal_to<int>();
ops["!="] = std::not_equal_to<int>();
ops[">"]  = std::greater<int>();
ops["<"]  = std::less<int>();
ops[">="] = std::greater_equal<int>();
ops["<="] = std::less_equal<int>(); 

Using:

bool resultOfComparison = ops[str](salary[i], 9000);

(see this link for a full working example.)


EDIT:

@sbi , map[key] , . it = map.find(key). map.end(), , it->second. , .

+15

, std::map .

+1

. . . if-else.

0

- EVAL , .

EDIT: ++ EVAL .

0

, , ++, . , , ++ , .

0

, factory, ( ).

- :

: Comp cmp = Comp (str);

if (cpm ( [i], 9000)) {  cout < ""; }

0

"" !;) i.e.

template <typename T>
bool eval_op(const string& op, const T& lhs, const T& rhs)
{
  switch(op.size())
  {
    case 2:
    {
      switch(op[1])
      {
        case '=':
        {
          switch(op[0])
          {
            case '=': return lhs == rhs;
            case '!': return lhs != rhs;
            case '>': return lhs >= rhs;
            case '<': return lhs <= rhs;
          }
        }
        default: throw("crazy fool!");
      };
    }
    case 1:
    {
      switch(op[0])
      {
        case '>': return lhs > rhs;
        case '<': return lhs < rhs;
        default: throw ("crazy fool!");
      }
    }
    default: throw ("crazy fool!");
  }

  return false;
}

: ... ...

0

if-else . , , , .

if( in == "==" )
    cond = salary[i] == 9000;
else if( in == "!=" )
    cond = salary[i] != 9000;
// ...
else
  // throw, return -1, raise a flag or burst out in laughter

, eval(), . , , Little Bobby Tables.

, , - . , . , , 6 . 7, .

0
source

Source: https://habr.com/ru/post/1770726/


All Articles