首页 > 代码库 > STL学习笔记

STL学习笔记

set:插入后自动按从小到大的顺序排列,如果是结构体的话需要重载<,集合内元素不允许重复。

 

set的一些操作见代码:

#include <iostream>#include <set>using namespace std;typedef struct tagStudentInfo{  int nID;  string strName;  bool operator <(tagStudentInfo const& _A) const//升序排列    {     if(nID<_A.nID)      return true;     if(nID == _A.nID)     return strName.compare(_A.strName) < 0;        return false;    }}sInfo,*PsInfo;int main(){  set<sInfo>setS;  sInfo stuInfo;  stuInfo.nID = 10;  stuInfo.strName = "test1";  setS.insert(stuInfo);    stuInfo.nID = 20;  stuInfo.strName = "test2";  setS.insert(stuInfo);  set<sInfo>::iterator sIter;  for(sIter=setS.begin(); sIter!=setS.end(); sIter++)  {    cout <<(*sIter).nID <<" "<< (*sIter).strName << endl;  }  set<int>a;  set<int>b;  set<int>c;  set<int>d;  set<int>e;     a.insert(1);  a.insert(2);  a.insert(3);  a.insert(4);  a.insert(5);  b.insert(3);  b.insert(4);  b.insert(5);    set_union(a.begin(), a.end(), b.begin(), b.end(), inserter(c, c.begin()));  set<int>::iterator s;  for(s=c.begin(); s!=c.end(); s++)  {    cout <<(*s)<<",";  }  cout << endl;    set_intersection(a.begin(), a.end(), b.begin(), b.end(), inserter(d, d.begin()));  for(s=d.begin(); s!=d.end(); s++)  {    cout <<(*s) <<",";  }  cout << endl;    set_difference(a.begin(), a.end(), b.begin(), b.end(), inserter(e, e.begin()));  for(s=e.begin(); s!=e.end(); s++)  {    cout <<(*s)<<",";  }  cout <<endl;    return 0;}    

 

STL学习笔记