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

C++ comparison using strings for operators

本文关键字:比较 字符串 运算符 C++      更新时间:2023-10-16

我正在写下面的函数,并开始认为可能有更好的方法来实现它;但是谷歌并没有出现太多,所以任何见解都将不胜感激。我也有一个非常类似的情况,涉及整数。

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;
    }
}

您可以使用映射来存储运算符和相关函子。在 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>()}
};

您还可以在操作中看到它。像这样的方法的好处是,包含更多运算符非常容易,因为您所要做的就是将它们添加到地图中。

正如其他人所提到的,您应该首先问自己为什么要这样做 - 可能有更好的解决方案。 不过,我可能会做这样的事情:

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");
    }
}