map容器练习:使用map容器识别统计单词个数

题目链接:单词识别_牛客题霸_牛客网

对map的使用不太熟悉的同学可以参考:超详细介绍map(multimap)的使用-CSDN博客

题目解析

输入一个英文句子,把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来,次数一样的按照单词小写的字典序排序输出,要求能识别英文单词和句号

得到单词与其个数,我们会用到map容器。输出要求:个数多的先输出,个数相同按照字典序排序输出

算法分析

其实具体思路很简单,主要是对于map容器使用的练习

1.输入一个句子,依次得到单词,并使用map容器记录单词及其个数。

2.因为map是按照字典序排序的,所以我们需要按照单词个数重新排序,map本身是不支持sort,所以我们将map的数据放入vector中进行排序(pair本身是支持排序的,但是它支持的排序,并不是我们所需要的排序,所以我们要传入仿函数实现自己定义的排序)

3.排序完成我们输出结果即可

代码实现

cpp 复制代码
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
using namespace std;

struct compare
{
    bool operator()(const pair<string, int>& a, const pair<string, int>& b)
    {
        //当个数相同时,按照字典序排序
        if (a.second == b.second)
            return a.first < b.first;
        return a.second > b.second;
    }
};

int main()
{
    string in;
    getline(cin, in);
    //将单词存入数组
    vector<string> word;
    string tmp;
    for (auto& e : in)
    {
        if (e == ' ' || e == '.')
        {
            word.push_back(tmp);
            tmp.resize(0);
        }
        else
            tmp += e;
    }
    //使用map容器得到单词以及其个数
    map<string, int> ret;
    int num = 'a' - 'A';
    for (auto& r : word)
    {
        string e = r;
        if (r[0] >= 'A' && r[0] <= 'Z')
        {
            e[0] += num;
        }
        ret[e]++;
    }
    //放入vector进行排序
    vector<pair<string, int>> amd;
    for (auto& e : ret)
    {
        amd.push_back(e);
    }

    sort(amd.begin(), amd.end(), compare());

    for (auto& e : amd)
    {
        cout << e.first << ":" << e.second << endl;
    }
}

优化:可以直接将单词放入map,没必要多先放入vector再放入map

cpp 复制代码
#include<iostream>
#include<map>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;

// operator()
struct compare
{
	bool operator()(const pair<string, int>& a, const pair<string, int>& b)
	{
		if (a.second == b.second)
            return a.first < b.first;
        return a.second > b.second;
	}
};

int main()
{
	string in;
	getline(cin,in);
	string tmp;
	map<string, int> ret;
	for (auto& e : in)
	{
		if (e == '.' || e == ' ')
		{
			ret[tmp]++;
			tmp.resize(0);
		}
		else
		{
			tmp += tolower(e);//大写转小写函数。小写转大写:toupper
		}
	}

	vector<pair<string, int>> n;
	for (auto& e : ret)
	{
		n.push_back(e);
	}
	sort(n.begin(), n.end(), compare());
	for (auto& e : n)
	{
		cout << e.first << ":" << e.second<<endl;
	}
}
相关推荐
不知天地为何吴女士42 分钟前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界42 分钟前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
wjs20242 小时前
状态模式(State Pattern)
开发语言
我命由我123452 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
励志要当大牛的小白菜3 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970443 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵4 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子5 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男6 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展