赞助

C++的STL之map自动排序特性

#include <iostream>
#include <map>
using namespace std;

int main()
{
方法一: map
<int,int> m; srand((unsigned)time(NULL)); for (int i =0; i< 100; i++) { int key = rand()%100+1;//1~100的随机数 int value = rand()%2;//0或1随机数 printf("第%d次插入前:key=%d, value=%d\n",i+1,key,value); m.insert(pair<int,int>(key,value)); } printf("\n"); map<int,int>::iterator iter; for (iter = m.begin(); iter != m.end(); iter++) { printf("key:%d, value:%d\n",iter->first,iter->second); } printf("\n"); return 0; }

 

 

自动排序:

 方法二(26个英文字母):

#include <iostream>
#include <map>
using namespace std;

int main()
{
    map<int,int> mc;
    srand((unsigned)time(NULL));

    for (char c='z'; c >= 'a'; c--)
    {
        int num = rand()%2;
        printf("%c,  %d\n",c,num);
        mc.insert(pair<char,int>(c,num));
    }

    printf("\n");


    map<char,int>::iterator iter;

    for (iter = mc.begin(); iter!=mc.end(); iter++)
    {
        printf("key= %c, value=%d\n",iter->first,iter->second);
    }

    printf("\n");
    return 0;
}

 

遍历map:

 

posted @ 2018-05-22 23:55  车臣  阅读(13747)  评论(0编辑  收藏  举报