【C++ Primer】STL容器Map(二)

2014-11-24 12:03:58 · 作者: · 浏览: 1
//两个 map 容器的大小比较是基于第一个不相同的元素的大小比较。
{ //两个 map 容器相等,当且仅当它们的元素个数相等且同一个位置上的值相等
map ctr1,ctr2;
int i;
for(i=0;i<3;i++)//下面给 ctr1 和 ctr2 赋值
{
ctr1.insert(pair (i,i));
ctr2.insert(pair (i,i+1));
}
if(ctr1 cout<<"ctr1 else
cout<<"ctr1>=ctr2"< }

void reverse_map()//打印 反向 map rbegin() rend()跟 reverse_iterator同时使用
{
map ::reverse_iterator rcp;
for(rcp=ctr.rbegin();rcp!=ctr.rend();rcp++)
cout<<"("<first<<" , "<second<<") ";

}

void swap_map()
{

map ctr1, ctr2;
map ::const_iterator cp;
int i;

for(i=0;i<3;i++)//下面先给 ctr1 和 ctr2 赋值
{
ctr1.insert(pair (i,i));
ctr2.insert(pair (i,i+10));
}
cout<<"Before exchange with ctr2 the ctr1 is:";


for(cp=ctr1.begin();cp!=ctr1.end();cp++)//让 cp 从 c 的开始到结束打印 cp 对应的值
cout<<"("<first<<" , "<second<<") ";

cout< cout<<"After exchange with ctr2 the ctr1 is:";
ctr1.swap(ctr2);//让 ctr1 的内容与 ctr2 交换
for(cp=ctr1.begin();cp!=ctr1.end();cp++)//让 cp 从 c 的开始到结束打印 cp 对应的值
cout<<"("<first<<" , "<second<<") ";
cout< }
int main()
{

creat_map();
int i;

cout<<"1,测试begin()"< cout<<"2,测试count()求某关键字个数"< cout<<"3,测试test_equal_range()"< cout<<"4,测试erase()"< cout<<"5,测试key_compare_map()"< cout<<"6,测试lower_bound_map()"< cout<<"7,测试map size和 max_size(最大可能长度)"< cout<<"8,测试符号 [] 的作用"< cout<<"9,测试符号 != 的作用"< cout<<"10,测试符号 < 的作用"< cout<<"11,打印反向map"< cout<<"12,交换两个map 的值"< while(1)
{
cin>>i;

switch(i)
{
case 1: print_first_element(); break;
case 2: int j;
j=ctr.count(1);//求出关键字为 1 的元素的个数(由于map 容器的关键字是惟一的,故它只能取 0 或者 1)
cout<<"The number of key 1 is: "< case 3: test_equal_range(); break;
case 4: erase_map();break;
case 5: key_compare_map();break;
case 6: lower_bound_map();break;
case 7: cout<<"the size of ctr is:"< cout<<"the max_size of ctr is:"< case 8: cout<<"before change map is:"< print();
ctr[1]='W';//将关键字为 1的对应值变为 W
ctr[7]; //添加一个关键字为7 值为0的项
cout<<"\nafter change map is:"< print();break;

case 9:compare_map();break;
case 10:comp_map();break;
case 11:reverse_map();break;
case 12:swap_map(); break;
}

}
map ::iterator end;//迭代器
end=ctr.end(); //这里定位到Map 中最后一个元素后面位置,所以什么都不打印
//end--;//这定位到最后一个元素 d 除去了重复关键字 c
cout<<"The last element is:"<second<

clear_map();


return 0;
}


摘自 小田的专栏