容器(未完....)

Set集合容器

Set不会重复插入相同键值的元素,采取忽略处理,可去重 ,Set在插入元素时可直接排序。

以下面的代码为例:

题目网址:https://www.hackerrank.com/challenges/cpp-sets/problem

#include<stdio.h>
#include<set>
#include<iostream>
using namespace std;
int main()
{
    //定义元素类型为int的集合对象s,当前没有任何元素
    set<int>s;  //创建set对象
    set<int>::iterator it;   //定义前向迭代器
    int n,i,a,b;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d %d",&a,&b);
        if(a==1)
            s.insert(b);   //插入元素
        else if(a==2)
            s.erase(b);   //删除元素
        else if(a==3)
        {
            it=s.find(b); //查找键值为b的元素
            if(it!=s.end()) //找到
                printf("Yes\n");
            else
                printf("No\n");
        }
    }
    return 0;
}

以下只是一个输出,与上题无关

//例:输入 1 12 6 8
//使用cout需要头文件#include<iostream>
set<int>::iterator it;   //定义前向迭代器
for(it=s.begin();it!=s.end();it++)
{
    cout<<*it<<" ";
}
//输出 1 6 8 12


//反向遍历集合中的元素
set<int>::reverse_iterator rit;//定义反向迭代器
for(rit=s.begin();rit!=s.rend();rit++)
{
    cout<<*rit<<" ";
}
//输出12 8 6 1

map映照容器

插入元素的键值不允许重复

题目网址:https://www.hackerrank.com/challenges/cpp-maps/problem

#include<stdio.h>
#include<map>
#include<string.h>
#include<iostream>
using namespace std;
char s[100];
int main()
{
    int n;
    map<string,int>m; 定义map对象,当前没有任何元素
    scanf("%d",&n);
    int i,a,b;
    for(i=0;i<n;i++)
    {
        scanf("%d",&a);
        if(a==1)
        {
            scanf("%s %d",s,&b);
            //元素插入:  m[s]=b;   s是字符串
            m[s]+=b;
        }
        if(a==2)
        {
            scanf("%s",s);
            m.erase(s);//删除元素
        }
        if(a==3)
        {
            scanf("%s",s);
            printf("%d\n",m[s]);
        }
    }
    return 0;
}

输出


//前向遍历元素
map<string,int>::iterator it;
for(it=m.begin();it!=m.end;it++)
{
    //输出键值与映照数据
    cout<<(*it).first<<" : "<<(*it).second<<endl;
}
//反向遍历元素
map<int,char>m;
map<int,char>::reverse_iterator rit;
for(rit=m.rbegin();rit!=m.rend();rit++)
{
    //输出键值与映照数据
    cout<<(*rit).first<<" : "<<(*rit).second<<endl;
}

元素的搜索


map<int,char>::iterator it;
it=m.find(x);
if(it!=m.end())
{
    cout<<(*it).first<<" : "<<(*it).second<<endl;
}
else 
{
    cout<<"not found it"<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值