C++ comparing bunch of values with a given one

后端 未结 10 1062
一向
一向 2021-01-21 06:02

I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util

10条回答
  •  我在风中等你
    2021-01-21 06:58

    For your request to do

    if (InSet(value)(GetValue1(), GetValue2(), GetValue3()))
    {
       // Do something here...
    }
    

    Try this:

    template 
    class InSetHelper
    {
         const T &Value;
         void operator=(const InSetHelper &);
    public:
         InSetHelper(const T &value) : Value(value) {}
    
         template
         bool operator()(const Other &value1, const Another &value2) const
         {
             return Value == value1 || Value == value2;
         }
         template
         bool operator()(const Other &value1, const Another &value2, const AThird &value3) const
         {
             return Value == value1 || Value == value2 || Value == value3;
         }
    };
    
    template  
    InSetHelper InSet(const T &value) { return InSetHelper(value); }
    

    This syntax might be more clear though:

    if (MakeSet(GetValue1(), GetValue2(), GetValue3()).Contains(value))
    {
       // Do something here...
    }
    
    template 
    class Set3
    {
        const T& V1;
        const U& V2;
        const V& V3;
        void operator=(const Set3 &);
    public:
        Set3(const T &v1, const U &v2, const V &v3) : V1(v1), V2(v2), V3(v3) {}
    
        template 
        bool Contains(const W &v) const
        {
            return V1 == v || V2 == v || V3 == v;
        }
    };
    
    template 
    class Set2 
    { 
         // as above 
    };
    
    template 
    Set3 MakeSet(const T &v1, const U &v2, const V &v3)
    {
        return Set3(v1, v2, v3);
    }
    
    template 
    Set3 MakeSet(const T &v1, const U &v23)
    {
        return Set3(v1, v2);
    }
    

    If those values are really part of a tree or a linked list, then you have your set/container already, and your best bet is to just use some recursion:

    parent.ThisOrDescendantHasValue(value);
    

    You'd just add this to whatever class parent and child belong to:

    class Node
    {
    public: 
        Value GetValue();
        Node *GetChild();
        bool ThisOrDescendantHasValue(const Value &value)
        {
            return GetValue() == value
               || (GetChild() && GetChild->ThisOrDescendantHasValue(value));
        }
    };
    

提交回复
热议问题