STL (Standard Template Library) in C + + is very convenient, here we summarize .
First, set
Set is a standard associative container in STL (Vector,list,string,deque is a sequence container, and Set,multiset,map,multimap is a standard associative container), which is implemented using a balanced search tree-red and black trees. Insert delete operation only need pointer operation node to complete, do not involve memory move and copy, so efficiency is high.
Elements are unique in set, and the elements are automatically sorted in ascending order by default, supporting the intersection (set_intersection) of the set, the difference (set_difference) and (set_union), the symmetry difference (set_symmetric_ difference) and so on some set of operations, if you need the elements in the collection to allow repetition then you can use Multiset.
1) insertion (insert)
The set element is added using the Insert () method, as shown in the following example:
1#include <bits/stdc++.h>2 using namespacestd;3 4 intMain () {5 Set<int>s;6 intN;7cout <<"Input:";8 for(inti =0; I <5; i++){9CIN >>N;Ten S.insert (n); One } Acout <<"Output:"; - for(Set<int>::iterator it = S.begin (); It! = S.end (); ++it) { -cout << *it <<' '; the } -}
The results of the operation are as follows:
The visible set has removed the same element for us and is output by default in ascending order. If we want to construct an ascending set, we can declare this:set<int, greater<int>> s;
2) Calendar
The set's calendar is typically iterator with an iterator, which is the encapsulation of the pointer, as shown in the example code above.
3) Initialization
We can use arrays for initialization, or copy constructors:
1 int Main () {2 int a[3] = {123}; 3 set<int3); 4 set<intSETB (SetA); 5 }
4) Set, intersection, difference set
The set method can be used to easily find the convergence, intersection and difference set:
1#include <bits/stdc++.h>2 using namespacestd;3 4 intMain () {5 inta[3] = {1,2,3};6 intb[4] = {1,2,4, -1};7 Set<int> SetA (A, A +3);8 Set<int> Setb (b, B +4);9 Set<int>Set1, Set2, Set3;Ten OneSet_union (Seta.begin (), Seta.end (), Setb.begin (), Setb.end (), insert_iterator<Set<int>>(Set1, Set1.begin ())); ASet_intersection (Seta.begin (), Seta.end (), Setb.begin (), Setb.end (), insert_iterator<Set<int>>(Set2, Set2.begin ())); -Set_difference (Seta.begin (), Seta.end (), Setb.begin (), Setb.end (), insert_iterator<Set<int>>(Set3, Set3.begin ())); - thecout <<"Union:"; - for(Set<int>::iterator it = Set1.begin (); It! = Set1.end (); ++it) cout << *it <<' '; cout <<Endl; - -cout <<"intersection:"; + for(Set<int>::iterator it = Set2.begin (); It! = Set2.end (); ++it) cout << *it <<' '; cout <<Endl; - +cout <<"difference:"; A for(Set<int>::iterator it = Set3.begin (); It! = Set3.end (); ++it) cout << *it <<' '; cout <<Endl; at}
The parameters of the three functions are similar and run as follows:
To IS continued.
C + + STL templates