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

前端 未结 10 1993
春和景丽
春和景丽 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:28

    I was able to write a general contains function for std::list and std::vector,

    template
    bool contains( const list& container, const T& elt )
    {
      return find( container.begin(), container.end(), elt ) != container.end() ;
    }
    
    template
    bool contains( const vector& container, const T& elt )
    {
      return find( container.begin(), container.end(), elt ) != container.end() ;
    }
    
    // use:
    if( contains( yourList, itemInList ) ) // then do something
    

    This cleans up the syntax a bit.

    But I could not use template template parameter magic to make this work arbitrary stl containers.

    // NOT WORKING:
    template class STLContainer, class T>
    bool contains( STLContainer container, T elt )
    {
      return find( container.begin(), container.end(), elt ) != container.end() ;
    }
    

    Any comments about improving the last answer would be nice.

提交回复
热议问题