使用字符串进行运算符的C ++比较

时间:2012-10-12 19:33:59

标签: c++ operators compare string-comparison

我正在写下面的功能,并开始认为可能有更好的方法去做;然而谷歌并没有出现太多,所以任何见解都会受到赞赏。我也有一个非常类似的情况涉及整数。

bool compare_strs (std::string operator_, std::string str_0, std::string str_1)
{
    if (operator_ == ">")
    {
        return str_0 > str1;
    }
    else if (operator_ == "<")
    {
        return str_0 < str1;
    }
    else if (operator_ == "<=")
    {
        return str_0 <= str1;
    }
    else
    {
        return str_0 >= str1;
    }
}

2 个答案:

答案 0 :(得分:3)

您可以使用地图存储运算符和相关的仿函数。在C ++ 11中,沿着这些方向的东西应该可以工作,尽管可能会有一些微妙的错误。在C ++ 03中,您必须更改一些内容,包括将std::function更改为boost::function或函数指针,以及使用std::make_pair来存储地图值。

#include <functional> //for std::function and std::less et al.
#include <map> //for std::map
#include <stdexcept> //for std::invalid_argument
#include <string> //for std::string

struct StringComparer {
    static bool compare( //split up to fit width
        const std::string &oper, 
        const std::string &str0, const std::string &str1
    ) {
        MapType::const_iterator iter = operations.find(oper); 
        if (iter == std::end(operations)) //check if operator is found
            throw std::invalid_argument("No match for provided operator.");

        return iter->second(str0, str1); //call the appropriate functor
    }

private:
    using MapType = std::map< //makes life easier, same as typedef
        std::string, 
        std::function<bool(const std::string &, const std::string &)>
    >;

    static const MapType operations; //a map of operators to functors
};

const StringComparer::MapType StringComparer::operations = { //define the map
    {"<", std::less<std::string>()}, //std::less is a functor version of <
    {"<=", std::less_equal<std::string>()},
    {">", std::greater<std::string>()},
    {">=", std::greater_equal<std::string>()}
};

您也可以see it in action。这种方法的好处在于,包含更多运算符非常容易,因为您只需将它们添加到地图中即可。

答案 1 :(得分:0)

正如其他人所说,你应该先问问自己为什么要这样做 - 可能有更好的解决方案。尽管如此,我可能会这样做:

template <typename T1, typename T2>
bool mycompare(std::string operator_, const T1 & _lhs, const T2 & _rhs)
{
    if (operator_ == ">")
    {
        return _lhs > _rhs;
    }
    else if (operator_ == "<")
    {
        return _lhs < _rhs;
    } 
    //etc.
    else
    {
        throw new exception("Invalid operator");
    }
}