分享

c加加 set和map

 汉江秋月夜 2012-07-25
#include<map>
#include<iostream>
using namespace std;
int main(){                                 //main()不能返回void,否则会error: ‘::main’ must return ‘int’
    map<int,string> stu;      //定义map对象
    //向map中插入数据的4种方法
    stu.insert(pair<int,string>(1,"stu_one"));        //插入方法1
    stu.insert(map<int,string>::value_type(2,"stu_two"));     //插入方法2
    stu[3]="stu_three";                 //插入方法3
    stu[7]="stu_seven";
    stu[8]="stu_eight";
    stu[9]="stu_nine";
    //插入方法4,可以判断插入是否成功
    pair<map<int,string>::iterator,bool> Insert_Pair;
    Insert_Pair=stu.insert(pair<int,string>(1,"stu_one"));
    if(Insert_Pair.second==true)
        cout<<"Insert Successgully"<<endl;
    else
        cout<<"Insert Failure"<<endl;       /*输出Insert Failure*/
         
    map<int,string>::iterator iter;           //定义map迭代器
         
    //数据的查找.使用count或find
    for(int k=0;k<10;k++){
        if(!stu.count(k))           //count返回关键字出现的次数,没有出现则返回0
            cout<<"Don't find key=="<<k<<endl;
        else
            cout<<stu[k]<<endl;     //stu[k]是key=k时对应的value值
    }
    iter=stu.find(1);
    if(iter!=stu.end())
        cout<<"Find,the value is "<<iter->second<<endl;
    else
        cout<<"Don't find key==1"<<endl;
 
    //数据的遍历,2种方法
    for(iter=stu.begin();iter!=stu.end();iter++){       //使用迭代器遍历
        cout<<iter->first<<"  "<<iter->second<<endl;
    }
    int nSize=stu.size();                   //获取map集合元素的个数
    for(int i=0;i<nSize;i++)             //使用下标遍历.i从0到5.使用下标直接访问的是value值
        cout<<stu[i]<<endl;     /*注意这里的下标不同于数组的下标,这里的下标指的就是key值.所以只有当i为1,2,3时才有打印输出*/
 
 
    //数据的删除与清空
    //用clear()清空,用empty()判断是否为空
    iter=stu.find(2);       //用迭代器使用erase删除
    stu.erase(iter);
 
    stu.erase(3);           //使用关键字来删除
    //把以下的元素全部清除
    stu.erase(stu.begin(),stu.end());
     
    for(iter=stu.begin();iter!=stu.end();iter++){
        cout<<iter->first<<"  "<<iter->second<<endl;
    }
     
    return 0;
}

原文来自:博客园(华夏35度)http://www.cnblogs.com/zhangchaoyang 作者:Orisun
分类: Algorithms
0
0
(请您对文章做出评价)
博主前一篇:开源软件许可协议简介
博主后一篇:微软学术搜索新特征暴光

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多