C + + STL set common functions Daquan

Source: Internet
Author: User
Tags sorts


C + + STL Collection Set Introduction C + + STL collection (set) is an associative container that contains sorted objects. Set/multiset automatically sorts the elements according to the sort criteria that are pending. The difference is that the former does not allow elements to be duplicated, while the latter allows. 1) can not directly change the value of the element, because that will upset the original ...


Introduction to C + + STL collection set

A C + + STL collection (set) is an associative container that contains sorted objects. Set/multiset automatically sorts the elements according to the sort criteria that are pending. The difference is that the former does not allow elements to be duplicated, while the latter allows.

1) cannot directly change the element value, because that will upset the original correct order, to change the element value must first delete the old element, then insert the new element

2) Any operator function that does not provide direct access to the element can only be accessed indirectly through an iterator, and the element value is constant from an iterator perspective

3) The element comparison action can only be used for the same type of container (i.e. the element and collation must be the same)

Set Template prototype://key as Element (key value) type


Template <class Key, class Compare=less<key>, Class Alloc=stl_default_allocator (key) >

As you can see from the prototype, you can see that the comparison function object and the memory allocator are using default parameters, so if not specified, they will take the system default.


The list of member functions for the set is as follows:

C + + STL container SET member function: Begin ()--Returns an iterator to the first element

C + + STL container SET member function: Clear ()--Clears 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 collection is empty

C + + STL container SET member function: End ()--Returns an iterator pointing to the last element

C + + STL container set member function: Equal_range ()--returns two iterators in the collection with the upper and lower bounds equal to the given value

C + + STL container SET member function: Erase ()--delete an element from the collection

C + + STL container SET member function: Find ()--Returns an iterator that points to the element being found

C + + STL container set member function: Get_allocator ()--the allocator that returns the collection

C + + STL container SET member function: Insert ()--insert element in collection

C + + STL container set member function: Lower_bound ()--Returns an iterator that points 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 limit of the elements that the set can hold

C + + STL container set member function: Rbegin ()--Returns a reverse iterator pointing to the last element in the collection

C + + STL container set member function: Rend ()--Returns a reverse iterator pointing to the first element in the collection

C + + STL container SET member function: Size ()--number of elements in the collection

C + + STL container set member function: Swap ()--swap two set variables

C + + STL container set member function: Upper_bound ()--Returns an iterator that is greater than a value element

C + + STL container set member function: Value_comp ()--Returns a function to compare the values between elements


C + + STL collection set insertion, traversal usage example

#include <iostream> #include <set> using namespace std; The set Insert element operation  Int main () {     ///defines an int type collection Object S, which currently does not have any elements. Collected and collated by www.169it.com    set<int> s;     S.insert (8);  Insert 8 for the first time,      S.insert (1) can be inserted;     S.insert (n);     S.insert (6);     S.insert (8);   Insert 8 for the second time, repeat the element, do not insert      set<int>::iterator it;//define the forward iterator//to     iterate through all elements in the collection for      (It=s.begin (); it!= S.end (); it++)     cout<<*it<<endl;        System ("pause");     return 0; }


A more detailed example of usage.

#include <iostream> #include <string> #include <set>using namespace std;struct strless{bool operator (   ) (const char *S1, const char *s2) const {return strcmp (S1, S2) < 0; }};void Printset (set<int> s) {copy (S.begin (), S.end (), ostream_iterator<int> (cout, ","));//Set<int >::iterator iter;//for (iter = S.begin (); ITER! = S.end (); iter++)////cout<< "set[" <<iter-s.begin () < < "]=" <<*iter<< ","; error//cout<<*iter<< ","; Cout<<endl;} void Main () {//Create set object, a total of 5 ways, indicating that if the comparison function object and memory allocator does not appear, that is, the system default mode//Create an empty set object, the element type is int,set<int> S1;//Create an empty set object, The element type char*, the Comparison function object (that is, the sorting criteria) for the custom Strlessset<const char*, strless> S2 (strless); Using Set object S1, copy generates set object S2set<int> S3 (S1); Create a set object int iarray[] with the element referred to in iteration interval [&first, &last] = {3, +, 19};set<int> S4 (IArray, IArray +);//with Iteration interval [& Amp;first, &last) refers to the element, and the comparison function object Strless, creates a set object const char* szarray[] = {"Hello", "dog", "Bird"};set<Const char*, strless> S5 (Szarray, Szarray + 3, strless ());//Element insert://1, insert value, return pair pairing object, can determine whether insert succeeds according to. second. (Hint: value cannot be duplicated with the element in the set container)//pair<iterator, bool> Insert (value)//2, inserts value before the POS position, returns the new element position, but does not necessarily insert success//iterator Insert (&pos, value)//3, inserts all elements in the iteration interval [&first, &last) into the set container//void Insert[&first, &last) cout< < "S1.insert ():" <<endl;for (int i = 0; I <5; i++) S1.insert (i*10);p rintset (S1);cout<< "s1.insert. Second =" <<endl;; if (S1.insert) second) cout<< "Insert ok!" <<endl;else cout<< "Insert failed!" <<endl;cout<< "S1.insert" second = "<<endl;if (S1.insert () second) {cout<<" Insert ok! " <<endl; Printset (s1);} else cout<< "Insert failed!" <<endl;cout<< "Pair<set<int>::iterator::iterator, bool> p;\np = S1.insert; \nif (P.second ): "<<endl;pair<set<int>::iterator::iterator, bool> p;p = S1.insert (); if (P.second) {cout<< "InseRT ok! " <<endl; Printset (s1);} else cout<< "Insert failed!" The <<endl;//element removes//1,size_type Erase (value) removes all elements within the set container that have the value of element, returns the number of elements removed//2,void erase (&pos) removes the element at POS position , no return value//3,void erase (&first, &last) removes elements from the iteration interval [&first, &last], no return value//4,void clear (), removes all elements within the set container cout << \ns1.erase = <<endl;s1.erase;p rintset (S1);cout<< "s1.erase" = "<<endl; S1.erase;p Rintset (S1);cout<< "Set<int>::iterator iter = S1.begin (); \ns1.erase (iter) =" <<endl; Set<int>::iterator iter = S1.begin (); S1.erase (ITER);p Rintset (S1);//Element lookup//count (value) returns the number of elements in the set object that have element values of value Iterator find (value) returns the location of value where value will return end ()//lower_bound (value), Upper_bound (value), Equal_range (value) Slightly cout<< "\ns1.count" = "<<s1.count (<<)", s1.count (+) = "<<s1.count" <<endl; cout<< "S1.find": "if (s1.find)! = S1.end ()) cout<<" ok! " <<endl;else cout<< "Not found!" <<endl;cout<< "S1.find": "if (s1.find)! = S1.end ()) cout<<" ok! " <<endl;else cout<< "Not found!" <<endl;//other commonly used functions cout<< "\ns1.empty () =" <<s1.empty () << ", s1.size () =" <<s1.size () < <endl;set<int> s9;s9.insert;cout<< "S1.swap (S9):" <<endl;s1.swap (S9);cout<< "S1:" <<endl;printset (S1);cout<< "S9:" <<endl;printset (S9);//lower_bound,upper_bound,equal_range (slightly)}


Custom comparison functions

When inserting an element into a collection using INSERT, the collection is placed on the node according to the Set Comparison function award. When defining a collection, if no comparison function is specified, the default comparison function is used, which is to insert the element in the order of the key values from small to large. In many cases, however, you need to write your own comparison function.

There are two ways to write a comparison function.

(1) If the element is not a struct, you can write a comparison function. The following program comparison rules are inserted into the collection in order of key values from large to small.

#include <iostream> #include <set>using namespace std;struct mycomp{//Custom comparison function, overloaded "()" operator bool Operator () ( const int &A, const int &b) {if (A! = b) Return a > B;elsereturn a > B;}}; int main () {set<int, mycomp> s;//Use comparison function Mycomps.insert (5),/////First insert 5, can insert S.insert (1); S.insert (6); S.insert (3); S.insert (5);  A second insert of 5, repeating elements, does not insert Set<int,mycomp>::iterator it;for (it = S.begin (); It! = S.end (); it++) cout << *it << " "; cout << Endl;return 0;} /* Run Result: 6 5 3 1  */

(2) If the element is a struct, then the comparison function can be written directly in the structure body.

#include <iostream> #include <set> #include <string>using namespace std;struct info{string name; Double Score;bool operator < (const Info &A) const//overloaded "<" operator, custom collation {//Sort by score from large to small. If you want to sort from small to large, use ">". return A.score < score;}}; int main () {set<info> 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<info>::iterator it;for ( it = S.begin (); It! = S.end (); it++) cout << (*it). Name << ":" << (*it). Score << Endl; return 0;} /* Run Result: tom:99jack:80steaven:60*/







Usage of the collection

#include <algorithm> #include <iostream> #include <set>using namespace std;       int main () {int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};             Set<int> S (A, A + 9);       int b[] = {3, 6, 8, 9};             Set<int> S2 (b, B + 4);        Set<int>::iterator site;       Set<int> Su;       Set<int> Si;       Set<int> Sd;             Set<int> SSD;                                   Intersection set_intersection (S.begin (), S.end (), S2.begin (), S2.end (),                                         Inserter (Si, Si.begin ())); Set_union (S.begin (), S.end (), S2.begin (), S2.end (), Inserter (Su, S                              U.begin ()));                                   Difference Set Set_difference (S.begin (), S.end (), S2.begin (), S2.end (),             Inserter (Sd, Sd.begin ())); Symmetric difference Set Set_symmetric_difFerence (S.begin (), S.end (), S2.begin (), S2.end (),                                                             Inserter (SSD, Ssd.begin ()));       site = Si.begin ();       cout<< "The intersection of S and S2 is:";              while (site! = Si.end ()) {cout<< *site << "";       + + site;             } cout<<endl;       site = Su.begin ();       cout<< "The union of S and S2 is:";              while (site! = Su.end ()) {cout<< *site << "";       + + site;             } cout<<endl;       site = Sd.begin ();       cout<< "The difference of S and S2 is:";              while (site! = Sd.end ()) {cout<< *site << "";       + + site;             } cout<<endl;       site = Ssd.begin ();       cout<< "The symmetric difference of S and S2 is:"; WhiLe (site! = Ssd.end ()) {cout<< *site << "";       + + site;             } cout<<endl; return 0;}




C + + STL set common functions Daquan

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.