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

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

    You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.

    For example: Suppose the set already has 20 as an element.

     std::set myset;
     std::set::iterator it;
     std::pair::iterator,bool> ret;
    
     ret=myset.insert(20);
     if(ret.second==false)
     {
         //do nothing
    
     }
     else
     {
        //do something
     }
    
     it=ret.first //points to element 20 already in set.
    

    If the element is newly inserted than pair::first will point to the position of new element in set.

提交回复
热议问题