系列文章目录
前言
《数据结构基础》c语言版 第2版,Ellis Horowitz著,朱仲涛译
2.7节,page77,习题1
一、题目描述
编写函数,读入一个字符串,统计字符串中不同字符的出现频率。
二、c++代码
1.方法1
代码如下:
#include<iostream>
#include <string.h>
#include <map>
using namespace std;
int main() {
string str="abcaaabbabc";
map<char,int>m;
for(auto &i:str)
m[i]++;
for(auto &i:m)
printf("%c" " " "%d\n",i.first,i.second);
system("pause");
return 0;
}
2.方法2
思路:先创建一个map,遍历字符串,逐个判断如果存在则count++,不存在则创建一个,让其value为1
代码如下:
#include<iostream>
#include <map>
using namespace std;
int main() {
string str="abcabcacab";
map<char,int>m;
for(int i=0;i<str.length();i++)
{
map<char,int>::iterator iter = m.find(str[i]);
if(iter!=m.end())
{
iter->second++;
} else
{
m.insert(pair<char,int>(str[i],1));
}
}
map<char,int>::iterator iter=m.begin();
for( ;iter!=m.end();iter++)
printf("%c" " " "%2d\n",iter->first,iter->second);
system("pause");
return 0;
}
map学习:
添加链接描述
2.方法3
思路:通过插入失败来增加字符的个数,如果插入失败则表明map中存在该字符,count++即可
代码如下:
#include<iostream>
#include <map>
using namespace std;
int main() {
string str = "abcabcacab";
map<char, int> m;
pair<map<char, int>::iterator, bool> result;
for (int i = 0; i < str.length(); i++) {
result = m.insert(pair<char, int>(str[i], 1));
if (result.second == false)
result.first->second++;
}
map<char, int>::iterator iter = m.begin();
for (; iter != m.end(); iter++)
printf("%c" " " "%2d\n", iter->first, iter->second);
system("pause");
return 0;
}