set容器应用实例

#include
#include
#include//pair要用到
#include
using namespace std;

class BlackList{
private:
set blacklist;
public:
BlackList(){}
~BlackList(){}
void Init();//初始化,set容器对象,用insert函数
void print()const;//添加const表示不改变成员变量,同时const也可用于重载(即带const与不带const实现重载)
bool findbl(string name);//查找是否在容器内,可用count函数实现
bool deletebl(string name);//删除元素,用erase函数

};
void BlackList::Init()
{
cout<<"please input the black name:\n";
string name;
while(cin>>name&&name!=string("1"))
{
pair::iterator,bool> it=blacklist.insert(name);//带一个键值参数的函数,返回一个pair类型
if(it.second==false)
cout<<"there is already exist!\nplease input the next one:";
}
}
void BlackList::print()const
{
set::const_iterator it=blacklist.begin();
while(it!=blacklist.end())
{
cout<<*it++<<'\t';
}
}
bool BlackList::findbl(string name)
{
if(blacklist.count(name))//计数,若存在则为1,不存在为0
return true;
else
return false;
}
bool BlackList::deletebl(string name)
{
if(findbl(name))
{
blacklist.erase(name);
return true;
}
else
return false;

}

int main()
{
BlackList bl;
bl.Init();//初始化
bl.print();//遍历
cout<<"please input what your find:\n";
string name;
cin>>name;
if(bl.findbl(name))//查找
cout<<"exist\n";
else
cout<<"not exist\n";
cout<<"please input what your want to delete:\n";
cin>>name;
if(bl.deletebl(name))//删除
cout<<"delete success\n";
else
cout<<"delete false\n"<<endl;
bl.print();

return 1;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值