簡體   English   中英

使用字符串進行運算符的C ++比較

[英]C++ comparison using strings for operators

我正在寫下面的函數,並開始認為可能有更好的方法去做; 然而谷歌並沒有出現太多,所以任何見解都會受到贊賞。 我也有一個非常類似的情況涉及整數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM