C + + set basic operations

Source: Internet
Author: User

1. Element insert: Insert ()
2. Middle sequence traversal: vector-like traversal (with iterators)
3. Reverse traversal: Use the reverse iterator reverse_iterator.
Cases:
Set<int> s;
......
Set<int>::reverse_iterator RIT;
For (Rit=s.rbegin (); Rit!=s.rend (); rit++)
4. Element removal: As with insertions, it can be efficiently removed and automatically adjusted to make the red-black tree balanced.
Set<int> s;
S.erase (2); Delete an element with a key value of 2
S.clear ();
5. Element search: Find (), if found, returns the position of the key-value iterator, otherwise, returns a position after the last element.
Set<int> s;
Set<int>::iterator it;
It=s.find (5); Find an element with a key value of 5
if (It!=s.end ())//Found
cout<<*it<<endl;
else//not found
cout<< "not Found";
6. Custom comparison functions
(1) The element is not a struct:
Cases:
Custom comparison function MyComp, overloaded "()" operator
struct MYCOMP
{
BOOL Operator () (const your_type &a,const your_type &b)
[
Return a.data-b.data>0;
}
}
set<int,mycomp>s;
......
Set<int,mycomp>::iterator it;
(2) If the element is a struct, the comparison function can be written directly in the structure body.
Cases:
struct INFO
{
String name;
Float score;
Overloaded "<" operator, custom collation
BOOL operator < (const Info &a) const
{
Press score to arrange from large to small
Return a.score<score;
}
}
Set<info> s;
......
Set<info>::iterator it;

Set_intersection (S.begin (), S.end (), S2.begin (), S2.end (), Inserter (Si, Si.begin ())); //Intersection
Set_union (S.begin (), S.end (), S2.begin (), S2.end (), Inserter (Su, Su.begin ())); //and set
Set_difference (S.begin (), S.end (), S2.begin (), S2.end (), Inserter (Sd, Sd.begin ())); //Difference set
Set_symmetric_difference (S.begin (), S.end (), S2.begin (), S2.end (), Inserter (SSD, Ssd.begin ())); //Symmetric difference set

C + + set basic operations

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.