map、vector、set的插入删除和查找解释及举例

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define N  10001
using namespace std;

int main()
{
    //删除都是erase(const_iterator position)函数
    //map的插入、查找
    cout<<"map:"<<endl;
    map<string,int>vis;
    //插入方式
    //1.vis.insert()
    vis.insert(make_pair<string,int>("bob",5));
    vis.insert(make_pair<string,int>("fan",9));
    vis.insert(make_pair<string,int>("jam",11));
    vis.insert(make_pair<string,int>("wang",32));
    //2.直接赋值
    vis["liu"]=18;
    map<string,int>::iterator it;//定义迭代器
    map<string,int>::value_type value1;//定义变量组合
    map<string,int>::key_type key1;
    //vis.count()返回被查找的元素的个数,因为map中不存在重复元素,所以返回值为0或者1,可以用来判断是否存在
    //vis.find()返回被查找元素的位置
    it=vis.find("bob");
    if(it==vis.end())
    {
        cout<<"No"<<endl;
    }
    else
    {
        cout<<"Yes"<<endl;
    }
    int num=vis.count("bob");
    cout<<num<<endl;
    vis.erase(it);
    num=vis.count("bob");
    cout<<num<<endl<<endl;
    //vector的插入查找
    cout<<"vector:"<<endl;
    vector<int>v;
    v.push_back(99);//向后不断push
    v.push_back(99);
    //v.insert();有三种用法
    //1.v.insert(const_iterator position,const_type val)向指定位置前插入一个元素,**并返回这个元素的迭代器**
    //2.v.insert(const_iterator position,const_size_type num,const_type val)向指定位置前插入num个值为val的元素
    //3.v.insert(const_iterator position,input_iterator start,input_iterator end)向指定位置前插入区间[start,end)的元素
    v.push_back(110);
    v.push_back(222);
    v.push_back(99);
    //vector没有查找函数,只能借助algortihm提供的find(),count()函数
    //如果想要获得索引,直接与begin()做差即可
    //algortihm中的count()只能对单个数字、字符进行记数
    vector<int>::iterator itv;
    itv=find(v.begin(),v.end(),99);
    if(itv==v.end())
    {
        cout<<"No"<<endl;
    }
    else
    {
        cout<<"Yes"<<endl;
    }
    itv=find(v.begin(),v.end(),100);
    if(itv==v.end())
    {
        cout<<"No"<<endl;
    }
    else
    {
        cout<<"Yes"<<endl;
    }
    num=count(v.begin(),v.end(),99);
    cout<<num<<endl<<endl;
    //set的插入、查找
    cout<<"set:"<<endl;
    set<int>s;
    s.insert(1);
    s.insert(1);
    s.insert(2);
    s.insert(9);
    set<int>::iterator its;
    its=s.find(9);
    if(its==s.end())
    {
        cout<<"No"<<endl;
    }
    else
    {
        cout<<"Yes"<<endl;
    }
    its=s.find(0);
    if(its==s.end())
    {
        cout<<"No"<<endl;
    }
    else
    {
        cout<<"Yes"<<endl;
    }
    num=s.count(1);//set自动排序去重,所以返回值只能是1或者0
    cout<<num<<endl;
    num=s.count(0);
    cout<<num<<endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值