C++ map 和 set容器

转载地址:http://blog.csdn.net/bingtang_blog/article/details/52730530

因为代码注释比较详尽,也就不多言语啦

map

#include<iostream>
#include<map>
using namespace std;
int main(){
    //map声明,加入有文件map 
    map<int, int> m;

    //插入元素要用makr_pair的方式 
    m.insert(make_pair(1, 5));

    //通过iterator来查找map里面的元素 
    map<int, int>::iterator ite;
    ite = m.find(1);
    //如果找到了,那么我们就删除掉原有的元素,加入新元素 
    //因为后来加入的元素如果键重复,不能覆盖,会被忽略 
    if(ite != m.end()){
        m.erase(1);
        m.insert(make_pair(1, 6));
    }else{
        //没找到直接加入 
        m.insert(make_pair(1, 6));
    }
    //用这种方式,来输出键值对的值 
    cout << ite->second << endl;

    //历遍map元素,并输出键值对 
    for(ite = m.begin(); ite != m.end(); ite++){
        cout << ite->first << "\t" << ite->second << endl;
    }
}

set:一维的map

#include<iostream>
#include<map>
#include<set>
using namespace std;
int main(){
    //声明集合,加入头文件<set> 
    set<int> s;

    //向集合中插入元素 
    s.insert(1);
    s.insert(2);
    s.insert(3);

    //在集合中查找元素 
    set<int>::iterator ite;
    ite = s.find(1);
    if(ite == s.end()){
        cout << "Not found" << endl;
    }else{
        cout << "Found" << endl;
    }

    //集合删除元素 
    s.erase(2);

    //在集合中查找元素的第二种方式 
    if(s.count(3) != 0){
        cout << "Found" << endl;
    }else{
        cout << "Not found" << endl; 
    }

    //历遍集合元素 
    for(ite = s.begin(); ite != s.end(); ite++){
        cout << *ite << endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值