map是stl中的映射类
以下是map的两个小程序:
1. 数字统计
int main()
{
// 统计数字出现频数
map<int,int> num_cnt;
int num[] = {1,2,3,4,5,2,3,4,5,3,4,5,4,5,5};
for ( int i = 0; i < sizeof(num)/sizeof(num[0]); i++ )
{
++num_cnt[num[i]];
}
for ( map<int,int>::iterator iter = num_cnt.begin(); iter != num_cnt.end(); iter++)
{
cout << iter->first <<": "<< num_cnt[iter->first]<<endl;
}
return 0;
}
输出:
char letters[]="编程之美 程序员面试宝典 c++primer advancedC++ 学习opencv 程序员面试宝典 c++primer";
char letters_excluded[]="advancedC++";
int main()
{
// 创建过滤集合
set<string> excluded;
map<string,int> word_cnt;
char* str;
int i;
if ('\n'==letters_excluded[strlen(letters_excluded)-1]) letters_excluded[strlen(letters_excluded)-1]='\0';
str = strtok(letters_excluded," ");
while (1)
{
if (!str) break;
excluded.insert( str );
i++;
str = strtok(NULL," ");
}
// 统计未被过滤单词出现频数
if ('\n'==letters[strlen(letters_excluded)-1]) letters[strlen(letters)-1]='\0';
str = strtok(letters," ");
while (1)
{
if (!str) break;
// 不在过滤词中则滤除掉
if ( !excluded.count(str))
{
++word_cnt[str];
}
i++;
str = strtok(NULL," ");
}
for ( map<string,int>::iterator iter = word_cnt.begin(); iter != word_cnt.end(); iter++)
{
cout << iter->first <<": "<< word_cnt[iter->first]<<endl;
}
return 0;
}
输出: