set is very useful in OI. Several common functions qwq are summarized.
#include<iostream> #include<cstdio> #include<set> //set Common usage of containers using namespace std; //Customized sorting rules can be achieved by using parody functions class R { public: bool operator()(const int &pre,const int &bac) { return pre>bac;//Guarantee that the sequence is larger before than after } }; set<int/*,R*/> s; //If you remove the comment, you will use a parody function. int main() { s.insert(5); s.insert(4); s.insert(3); s.insert(2); s.insert(1); for(set<int>::iterator i=s.begin();i!=s.end();i++) cout<<*i<<" "; //print 1 2 3 4 5 //erase cout<<endl<<"Erase"; cout<<endl<<s.erase(3)<<endl; //Delete successfully returns 1, otherwise return 0 for(set<int>::iterator i=s.begin();i!=s.end();i++) cout<<*i<<" "; //print 1 2 4 5 //uper_bound & lower_bound //uper_bound(x):Return s Medium satisfaction is greater than x Iterator of Minimum Element //lower_bound(x):Return s Medium satisfies greater than or equal to x Iterator of Minimum Element cout<<endl<<"uper_bound & lower_bound"; cout<<endl<<*s.upper_bound(3); //print 4 cout<<endl<<*s.lower_bound(3)<<endl; //print 4 cout<<endl<<*s.upper_bound(4); //print 5 cout<<endl<<*s.lower_bound(4)<<endl; //print 4 cout<<endl<<(s.lower_bound(6)==s.end())<<endl; //print 1 When none of the elements is greater than or equal to 6, the tail iterator is returned //insert cout<<endl<<"insert"<<endl; s.insert(6); for(set<int>::iterator i=s.begin();i!=s.end();i++) cout<<*i<<" "; //print 1 2 4 5 6 return 0; }
It's worth noting that when we change the rules with parody functions to make the sequence from big to small, the meaning of upper_bound and lower_bound is not what the annotations describe. Now the functions of these two functions will be very strange. Let me illustrate the functions of these two functions with a simple non-professional description for any situation.
lower_bound(x) :
- When there is an element equal to x in the container, return the element iterator
- Otherwise, assuming that x is inserted into the appropriate location of the container according to the arrangement rules of the container elements, the iterator of the next (right) element of X after the insertion is returned, and the tail iterator is returned if there are no elements.
exa.
- 653 221 x = 4, assuming that after insertion: 654 321, the iterator returns element 3
- %^ &* (, suppose inserting (suppose this is an ordered sequence),%^ &* (return iterator of element% at this time)
upper_bound(x) :
There are no rules for lower_bound(x). Same as others