欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++中set的增删查遍历实现教程

程序员文章站 2022-05-23 09:47:51
本文介绍set的增删查遍历实现,使用例子如下 下面程序统计出现的数字有哪些 #include #include using namespace std; int m...

本文介绍set的增删查遍历实现,使用例子如下

下面程序统计出现的数字有哪些

#include 
#include
using namespace std;
int main()
{
    int numList[6]={1,2,2,3,3,3};
    //1.set add
    set numSet;
    for(int i=0;i<6;i++)
    {
        //2.1insert into set
        numSet.insert(numList[i]);
    }
    //2.travese set
    for(set::iterator it=numSet.begin() ;it!=numSet.end();it++)
    {
        cout<<*it<<" occurs "<1.增加

调用insert成员函数,注意,set包含不重复的关键字,因此插入一个已经存在的元素对容器没有影响.

 numSet.insert(numList[i]);

2.遍历

使用set::iterator it;迭代器遍历

3.查找

使用find函数查找

使用如

if(numSet.find(findNum)!=numSet.end())

find 返回一个迭代器,如果查找失败会返回end()元素,否则成功

4.删除

erase的返回值总是0和1,若返回0,表示删除的元素不在set中,如

 int eraseReturn=numSet.erase(1);
;>