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

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

最佳答案

您可以使用映射来存储运算符和相关仿函数。在 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 .这种方法的好处是可以很容易地包含更多运算符,因为您所要做的就是将它们添加到 map 中。

关于C++ 比较使用运算符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12865884/

相关文章:

powershell - 比较对象多值 powershell

javascript - 如何在 JavaScript 中检查 null 值?

Java/Hibernate 比较器

c++ - 点燃 C++ : serialization class not found in cache store

c++ - Boost::asio::write上的互斥不起作用

c++ - 为什么我的代码无法编译? (完美转发和参数包)

r - 在应用族函数中使用反引号和运算符

c# - 为什么有人会在枚举声明中使用 << 运算符?

c++ - 是否可以在运行时切换到不同的基类构造函数?

c++ - C++ 中用于数组的等式和赋值运算符