您的位置:首页 > 编程语言 > C语言/C++

C++ stl set用法例子

2016-04-13 20:11 441 查看

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: