关联容器map实例

来源:互联网 发布:数据库设计包括 编辑:程序博客网 时间:2024/06/10 18:51
/*编译: g++ -o map map.cpp */#include<map>#include<cstring>#include<iostream>typedef std::map<int, std::string> UDT_MAP_INT_CSTRING;UDT_MAP_INT_CSTRING enumMap;int main(){    /*数组方式插值:如果元素是类对象,则开销比较大*/    /*它可以覆盖以前该关键字对应的值*/    enumMap[1] = "One";    enumMap[1] = "Two";//key: 1 value: Two    std::map<int, std::string>::iterator it;    for(it=enumMap.begin(); it!=enumMap.end(); ++it)        std::cout<<"key: "<<it->first <<" value: "<<it->second<<std::endl;    /*知道键,获取它的值*/    std::string str_handle = enumMap[1];    std::cout<<"str_handle "<<str_handle <<std::endl;    /*第一、二种插值方式*/    /*缺点:即当map中有这个关键字时,insert操作是插入数据不了的*/    enumMap.insert(std::pair<int, std::string>(2, "student_one"));     enumMap.insert(std::pair<int, std::string>(2, "student_two"));     /* it_key: 2 it_value: student_one */    std::map<int, std::string>::iterator it_it;    for(it_it=enumMap.begin(); it_it!=enumMap.end(); ++it_it)        std::cout<<"it_key: "<<it_it->first <<" it_value: "<<it_it->second<<std::endl;    enumMap.insert(std::map<int, std::string>::value_type(3, "student_three"));    enumMap.insert(std::map<int, std::string>::value_type(3, "student_four"));    std::map<int, std::string>::iterator it_two;    for(it_two=enumMap.begin(); it_two!=enumMap.end(); ++it_two)        std::cout<<"two_key: "<<it_two->first <<" two_value: "<<it_two->second<<std::endl;    return 0;}/***********************************结果:    key: 1 value: Two    str_handle Two    it_key: 1 it_value: Two    it_key: 2 it_value: student_one    two_key: 1 two_value: Two    two_key: 2 two_value: student_one    two_key: 3 two_value: student_three***********************************/
原创粉丝点击