STL set detailed usage

A collection (set) is a container, which contains the value of its elements is unique.

Use the library

#include <set>

 

definition

the easiest:

set<int> a;

set and other stl, as are support custom.

Because the set will automatically elements from small to large, so we can set its comparison function, where the priority queue is very similar.

Method 1 using a custom comparison function:

#include<stdio.h>
#include<set>
#include<string>
using namespace std;
struct People
{
    string name;
    int age;
};

struct cmp {
    bool operator  ()(People a, People b)
    {
        if(a.name==b.name)return false;
        return a.age<b.age;       //按照年龄由小到大进行排序
    }
};
 

set<People,cmp>s;

Method 2 operator overloading

#include <stdio.h> 
#include < SET > 
#include < String >
 the using  namespace STD;
 struct People 
{ 
    String name;
     int Age;
     BOOL  operator <( const People P) const   // operator overloading 
    {
         IF (name == P .name) return  to false ; // by name to re- 
        return Age <p.age;        // by age ascending sort 
    } 
 
}; 

SET <People> S;

Act 3 friend function

#include <bits / STDC ++ H.> the using namespace STD; struct People 
{ String name;
     int Age; 
    Friend BOOL operator <( const People A &, const   People & B)
     {
         IF (a.name == b.name) return to false ; // by name to re- return a.age <b.age;        // by age ascending sort     } 
}; SET <People> S;

 


      
        

 

Traversal

Also you need an iterator access:

set<People>::iterator it;
for(it=s.begin();it!=s.end();it++)  
{
    printf("姓名:%s 年龄:%d\n",(*it).name.c_str(),(*it).age);
}

Access set value of * t need to adopt the way.

 

Other uses:

the begin (); a first element address
Clear (); container set clear
COUNT (x); x number of elements
empty (); if empty
one element behind the last address; End ()
ERASE (x); Delete element X
Find (X); find an element x, return address, if there is no end returns
insert (x); adding elements X
size (); number of elements

Guess you like

Origin www.cnblogs.com/dyhaohaoxuexi/p/11324742.html