/*编译: 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
***********************************/
关联容器map实例
最新推荐文章于 2024-04-06 20:23:53 发布