C++ stl set用法例子

EG:

#include<stdio.h>

#include<string>

#include<set>

#include<iostream>

usingnamespace std;

intmain(){

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

       int j;

       set<int>::iterator it;

       set<int> 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 <iostream>
#include <set>
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 <iostream>
#include <set>
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 <iostream>
#include <set>
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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值