Comparison tricks in C++

前端 未结 10 1876
礼貌的吻别
礼貌的吻别 2021-01-31 16:13

A class:

class foo{
public:
    int data;
};

Now I want to add a method to this class, to do some comparison, to see if its data is equal to on

10条回答
  •  面向向阳花
    2021-01-31 16:24

    set is a good option, but if you really want to roll your own, initializer_list is convienient:

    bool is_in( int val, initializer_list lst )
    {
        for( auto i : lst )
            if( i == val ) return true;
        return false;
    }
    

    use is trivial:

    is_in( x, { 3, 5, 7 } ) ;
    

    it's O(n) thou, set / unordered is faster

提交回复
热议问题