字符串、散列--P1598 垂直柱状图

题目描述

写一个程序从输入文件中去读取四行大写字母(全都是大写的,每行不超过100个字符),然后用柱状图输出每个字符在输入文件中出现的次数。严格地按照输出样例来安排你的输出格式。

输入输出格式

输入格式:

四行字符,由大写字母组成,每行不超过100个字符

输出格式:

由若干行组成,前几行由空格和星号组成,最后一行则是由空格和字母组成的。在任何一行末尾不要打印不需要的多余空格。不要打印任何空行。

输入输出样例

在这里插入图片描述

思路

首先统计所有字符出现的次数,可以使用数组散列法或者直接使用map是实现,其次如何输出是本题的关键,方法是取得最高词频,作为输出控制台的高度,高度依次递减输出相应字符,如果词频小于高度输出空个否则输出*。(解题的过程中,发现set不可排序,无法使用sort())

AC1 数组散列+vector记录输出字符串

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
    string instr;
    int nums[26] = {0};
    for (int i = 0; i < 4; ++i) {
        getline(cin, instr);
        for (int j = 0; j < instr.size(); ++j) {
            //字符转数字
            int temp = instr[j] - 'A';
            //统计次数
            if (temp < 26 && temp > -1)nums[temp]++;
        }
    }
    //求取最大值
    int max = 0 ;
    for (int k = 0; k < 26; ++k) {
        if (nums[k]>max)max = nums[k];
    }
    vector<string> outstr;
    //生成输出的数组
    for (;max>0;max--) {
        for (int i = 0; i < 26; ++i) {
            if (nums[i] >= max){
                outstr.push_back("*");
                if (i!=25)outstr.push_back(" ");
            }
            else{
                outstr.push_back(" ");
                if (i!=25)outstr.push_back(" ");
            }
        }
        outstr.push_back("
");
    }
    //输出
    for (vector<string>::iterator iter =outstr.begin();iter!=outstr.end();++iter) {
        cout<<*iter;
    }
    char charpter ='A';
    for (int l = 0; l < 26; ++l) {
        cout<<charpter++;
        if(l!=25)cout<<" ";
    }
    return 0;
}

AC2

#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;

int main() {
    string instr;
    map<char, int> ma;
    for (int i = 0; i < 4; ++i) {
        getline(cin, instr);
        for (int j = 0; j < instr.size(); ++j) {
            int temp = instr[j] - 'A';
            //如果使用[]目前不属于map一部分的索引操作符访问某个键,则会自动为您添加一个键
            if (temp > -1 && temp < 26)ma[instr[j]]++;
        }
    }
    //取最高层
    int max = 0;
    for( map<char, int>::iterator  x = ma.begin();x!=ma.end();x++)
        if((*x).second>max)
            max = (*x).second;
    vector<string> outstr;
    //生成输出的数组
    for (;max>0;max--) {
        for (int i = 0; i < 26; ++i) {
            if (ma[i+'A'] >= max){

                outstr.push_back("*");
                if (i!=25)outstr.push_back(" ");
            }
            else{
                outstr.push_back(" ");
                if (i!=25)outstr.push_back(" ");
            }
        }
        outstr.push_back("
");
    }
    //输出
    for (vector<string>::iterator iter =outstr.begin();iter!=outstr.end();++iter) {
        cout<<*iter;
    }
    for ( map<char, int>::iterator iter=ma.begin();iter!=ma.end();iter++)
        cout << (*iter).first << " ";
    return 0;
}

学到的点

1 geline()可以用于输入多行字符串, 是他的默认结束符,一段结束其指针会跳转至结束符后所以可以输入多行字符串

原文地址:https://www.cnblogs.com/sunqiangstyle/p/10312283.html