How to check that an element is in a std::set?

前端 未结 10 1968
春和景丽
春和景丽 2020-11-30 17:13

How do you check that an element is in a set?

Is there a simpler equivalent of the following code:

myset.find(x) != myset.end()
10条回答
  •  既然无缘
    2020-11-30 17:30

    If you were going to add a contains function, it might look like this:

    #include 
    #include 
    
    template inline
    bool contains(TInputIterator first, TInputIterator last, const T& value)
    {
        return std::find(first, last, value) != last;
    }
    
    template inline
    bool contains(const TContainer& container, const T& value)
    {
        // This works with more containers but requires std::begin and std::end
        // from C++0x, which you can get either:
        //  1. By using a C++0x compiler or
        //  2. Including the utility functions below.
        return contains(std::begin(container), std::end(container), value);
    
        // This works pre-C++0x (and without the utility functions below, but doesn't
        // work for fixed-length arrays.
        //return contains(container.begin(), container.end(), value);
    }
    
    template inline
    bool contains(const std::set& container, const T& value)
    {
        return container.find(value) != container.end();
    }
    

    This works with std::set, other STL containers, and even fixed-length arrays:

    void test()
    {
        std::set set;
        set.insert(1);
        set.insert(4);
        assert(!contains(set, 3));
    
        int set2[] = { 1, 2, 3 };
        assert(contains(set2, 3));
    }
    

    Edit:

    As pointed out in the comments, I unintentionally used a function new to C++0x (std::begin and std::end). Here is the near-trivial implementation from VS2010:

    namespace std {
    
    template inline
        typename _Container::iterator begin(_Container& _Cont)
        { // get beginning of sequence
        return (_Cont.begin());
        }
    
    template inline
        typename _Container::const_iterator begin(const _Container& _Cont)
        { // get beginning of sequence
        return (_Cont.begin());
        }
    
    template inline
        typename _Container::iterator end(_Container& _Cont)
        { // get end of sequence
        return (_Cont.end());
        }
    
    template inline
        typename _Container::const_iterator end(const _Container& _Cont)
        { // get end of sequence
        return (_Cont.end());
        }
    
    template inline
        _Ty *begin(_Ty (&_Array)[_Size])
        { // get beginning of array
        return (&_Array[0]);
        }
    
    template inline
        _Ty *end(_Ty (&_Array)[_Size])
        { // get end of array
        return (&_Array[0] + _Size);
        }
    
    }
    

提交回复
热议问题