C++ stl set用法例子

EG:

#include

#include

#include

#include

usingnamespace std;

intmain(){

       int a[]={1,23,45,215,22,11,2,5,78,23};

       int j;

       set::iterator it;

       set myset(a,a+10);

      

       scanf("%d",&j);

      

       myset.insert(j);

       for(it=myset.begin();it!=myset.end();it++){

       cout<<*it<<" ";     

       }

 

getchar();getchar();getchar();

return0;

}

 

四个功能如下:

insert   插入元素。

erase   删除元素。

swap    替换元素。

clear     删除所有元素。

myset(数组名).insert(你要使用的功能名)(j(你要进行操作的变量));

 

Example

// erasing from set
#include 
#include 
using namespace std;

int main ()
{
  set<int> myset;
  set<int>::iterator it;

  // insert some values:
  for (int i=1; i<10; i++) myset.insert(i*10);  // 10 20 30 40 50 60 70 80 90

  it=myset.begin();
  it++;                                         // "it" points now to 20

  myset.erase (it);

  myset.erase (40);

  it=myset.find (60);
  myset.erase ( it, myset.end() );

  cout << "myset contains:";
  for (it=myset.begin(); it!=myset.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}
Output:
myset contains: 10 30 50


Example

// swap sets
#include 
#include 
using namespace std;

main ()
{
  int myints[]={12,75,10,32,20,25};
  set<int> first (myints,myints+3);     // 10,12,75
  set<int> second (myints+3,myints+6);  // 20,25,32
  set<int>::iterator it;

  first.swap(second);

  cout << "first contains:";
  for (it=first.begin(); it!=first.end(); it++) cout << " " << *it;

  cout << "\nsecond contains:";
  for (it=second.begin(); it!=second.end(); it++) cout << " " << *it;

  cout << endl;

  return 0;
}

Output:

first contains: 20 25 32
second contains: 10 12 75


 

Example

// set::clear
#include 
#include 
using namespace std;

int main ()
{
  set<int> myset;
  set<int>::iterator it;

  myset.insert (100);
  myset.insert (200);
  myset.insert (300);

  cout << "myset contains:";
  for (it=myset.begin(); it!=myset.end(); ++it)
    cout << " " << *it;

  myset.clear();
  myset.insert (1101);
  myset.insert (2202);

  cout << "\nmyset contains:";
  for (it=myset.begin(); it!=myset.end(); ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}

Output:

myset contains: 100 200 300
myset contains: 1101 2202

 

你可能感兴趣的