Search code examples
c++vectorcomparison-operators

comparison operator


It may be silly question. Is there any way to give comparison operator at runtime using string variable.
Suppose i have a data of salaries in vector.


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

The input given like above. I store the comparison operator in string str. str = (any comparison operator). Is there any way to check like this without if and switch.


salary str 9000


Solution

  • You can create a map with operator-strings as keys and function objects for corresponding comparison operations as values.


    Creating a map:

    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 it:

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

    (See this link for a complete working example.)


    EDIT:

    As @sbi said in the comments below, accessing a map using map[key] will create an entry if the key didn't exist. So use it = map.find(key) instead. If the result is equal to map.end() the key wasn't found, otherwise value is it->second. Take note of this while adapting this solution to your needs.