C ++ STL set common functions

Source: Internet
Author: User

C ++ STL set common functions

C ++ stl set introduction c ++ stl Set is an associated container that contains sorted objects. Set/multiset Automatically sorts elements based on the undetermined sorting criteria. The difference between the two lies in that the former does not allow repeated elements, while the latter does. 1) You cannot directly change the element value, because it will disrupt the original...

 

Introduction to c ++ stl set

The c ++ stl Set is an associated container that contains sorted objects. Set/multiset Automatically sorts elements based on the undetermined sorting criteria. The difference between the two lies in that the former does not allow repeated elements, while the latter does.

1) You cannot directly change the element value, because it will disrupt the original order. To change the element value, you must first Delete the old element, then Insert the new element.

2) any operation function that does not provide direct access to elements can only be indirectly accessed through the iterator. In terms of the iterator, the element value is a constant.

3) The element comparison action can only be used for containers with the same type (that is, the elements and sorting criteria must be the same)

Set template prototype: // Key is of the element (Key value) type.

 

 

template 
 
  , class Alloc=STL_DEFAULT_ALLOCATOR(Key) >
 

 

From the prototype, we can see that the comparison function objects and memory distributors use default parameters. Therefore, if they are not specified, they use the system default method.

 

The list of set member functions is as follows:

C ++ stl Container set member function: begin () -- returns the iterator pointing to the first element

C ++ stl Container set member function: clear () -- clear all elements

C ++ stl Container set member function: count () -- returns the number of elements of a value.

C ++ stl Container set member function: empty () -- returns true if the set is empty.

C ++ stl Container set member function: end () -- returns the iterator pointing to the last element

C ++ stl Container set member function: performance_range () -- returns two iterators with the upper and lower limits equal to the given values in the set.

C ++ stl Container set member function: erase () -- delete elements in the set

C ++ stl Container set member function: find () -- returns an iterator pointing to the searched Element

C ++ stl Container set member function: get_allocator () -- returns the set distributor.

C ++ stl Container set member function: insert () -- insert elements in the set

C ++ stl Container set member function: lower_bound () -- returns an iterator pointing to the first element greater than (or equal to) a value

C ++ stl Container set member function: key_comp () -- returns a function for comparing values between elements.

C ++ stl Container set member function: max_size () -- returns the maximum value of the elements that a set can contain.

C ++ stl Container set member function: rbegin () -- returns the reverse iterator pointing to the last element in the set.

C ++ stl Container set member function: rend () -- returns the reverse iterator pointing to the first element in the set.

C ++ stl Container set member function: size () -- number of elements in the set

C ++ stl Container set member function: swap () -- exchange two set variables

C ++ stl Container set member function: upper_bound () -- returns an iterator greater than a certain value element.

C ++ stl Container set member function: value_comp () -- returns a function used to compare values between elements.

 

C ++ stl set insert, traversal example

# Include
 
  
# Include
  
   
Using namespace std; // set insert element operation int main () {// defines an int type set object s. Currently, no elements exist. set is collected and sorted by www.169it.com.
   
    
S; s. insert (8); // insert 8 for the first time. You can insert s. insert (1); s. insert (12); s. insert (6); s. insert (8); // insert 8 for the second time. duplicate elements are not inserted.
    
     
: Iterator it; // defines the forward iterator. // traverses all elements in the set in the middle order for (it = s. begin (); it! = S. end (); it ++) cout <* it <
     
      

 

More detailed usage examples

 

# Include
       
        
# Include
        
         
# Include
         
          
Using namespace std; struct strLess {bool operator () (const char * s1, const char * s2) const {return strcmp (s1, s2) <0 ;}}; void printSet (set
          
           
S) {copy (s. begin (), s. end (), ostream_iterator
           
            
(Cout, ","); // set
            
              : Iterator iter; // for (iter = s. begin (); iter! = S. end (); iter ++) /// cout <"set [" <s1; // create an empty set object, element type char *, the comparison function object (that is, the sorting criterion) is a custom strLessset
             
               S2 (strLess); // use the set object s1 to copy and generate the set object s2set
              
                S3 (s1); // create a set object int iArray [] = {13, 32, 19} with the elements referred to by [& first, & last); set
               
                 S4 (iArray, iArray + 3); // use the elements referred to by [& first, & last) of the iteration interval, and compare the strLess function object, create a set object const char * szArray [] = {"hello", "dog", "bird"}; set
                
                  S5 (szArray, szArray + 3, strLess (); // element insert: // 1, insert value, return pair object, you can determine whether the insert is successful Based on. second. (Note: The value cannot be the same as the element in the set container) // pair
                 
                   Insert (value) // 2. insert the value before the pos position to return the position of the new element. However, the insert operation may fail. // iterator insert (& pos, value) // 3, insert all elements in the iteration interval [& first, & last) into the set container // void insert [& first, & last) cout <"s1.insert ():" <
                  
                    : Iterator, bool> p; \ np = s1.insert (60); \ nif (p. second): "<
                   
                     : Iterator, bool> p; p = s1.insert (60); if (p. second) {cout <"Insert OK! "<
                    
                      : Iterator iter = s1.begin (); s1.erase (iter); printSet (s1); // element lookup // count (value) returns the number of elements in the set object whose element value is value // iterator find (value) returns the position of the value. If no value is found, end () // lower_bound (value) is returned ), upper_bound (value), pai_range (value) slightly cout <"\ ns1.count (10) =" <
                     
                       S9; s9.insert (100); cout <"s1: =" "s9: =" "pre =" ">
                      

 

 

Custom comparison functions

When you use insert to insert an element into a set, the set will award the element to the set comparison function and place it on the node to which it is placed. When defining a set, if no comparison function is specified, the default comparison function is used, that is, the key values are inserted in sequence from small to large. However, in many cases, you need to write a comparison function by yourself.

There are two methods to compile a comparison function.

(1) If the element is not a struct, You can compile a comparison function. The following program comparison rule is to insert the key values from large to small to the set.

# Include
                       
                        
# Include
                        
                         
Using namespace std; struct mycomp {// custom comparison function, overload the "()" operator bool operator () (const int & a, const int & B) {if (! = B) return a> B; elsereturn a> B ;}}; int main () {set
                         
                          
S; // use the comparison function mycomps. insert (5); // insert 5 for the first time. You can insert s. insert (1); s. insert (6); s. insert (3); s. insert (5); // insert 5 for the second time. duplicate elements are not inserted.
                          
                           
: Iterator it; for (it = s. begin (); it! = S. end (); it ++) cout <* it <"; cout <endl; return 0 ;}/ * running result: 6 5 3 1 */
                          
                         
                        
                       

(2) If the element is a struct, you can directly write the comparison function in the structure.

 

# Include
                       
                        
# Include
                        
                         
# Include
                         
                          
Using namespace std; struct Info {string name; double score; bool operator <(const Info & a) const // reload the "<" operator, custom sorting rules {// sort by score from large to small. To sort data from small to large, use ">. Return a. score <score ;}}; int main () {set
                          
                           
S; Info info; // insert three elements info. name = "Jack"; info. score = 80; s. insert (info); info. name = "Tom"; info. score = 99; s. insert (info); info. name = "Steaven"; info. score = 60; s. insert (info); set
                           
                            
: Iterator it; for (it = s. begin (); it! = S. end (); it ++) cout <(* it ). name <":" <(* it ). score <endl; return 0 ;}/ * running result: Tom: 99 Jack: 80 Steaven: 60 */
                           
                          
                         
                        
                       


 

 

 

 

 

 

Set usage
 

# Include
                       
                        
# Include
                        
                         
Using namespace std; int main () {int a [] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; set
                         
                          
S (a, a + 9); int B [] = {3, 6, 8, 9}; set
                          
                           
S2 (B, B + 4); set
                           
                            
: Iterator site; set
                            
                              Su; set
                             
                               Si; set
                              
                                Sd; set
                               
                                 Ssd; // intersection set_intersection (S. begin (), S. end (), S2.begin (), S2.end (), inserter (Si, Si. begin (); // Union set_union (S. begin (), S. end (), S2.begin (), S2.end (), inserter (Su, Su. begin (); // set_difference (S. begin (), S. end (), S2.begin (), S2.end (), inserter (Sd, Sd. begin (); // set_symmetric_difference (S. begin (), S. end (), S2.begin (), S2.end (), inserter (Ssd, Ssd. begin (); site = Si. beg In (); cout <"the intersection of S and S2 is:"; while (site! = Si. end () {cout <* site <""; ++ site;} cout <
                                
                               
                              
                             
                            
                           
                          
                         
                        
                       

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.