扩展程序以计算行频 [英] Extending a program to count line frequency

查看:110
本文介绍了扩展程序以计算行频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的程序来计算字频率:

I have this simple program to count the word frequency:

#include <iostream>
#include <map>
#include <cctype>
#include <string>
using namespace std;
int main(void) {
  map<string, int> words;
  map<string, int>::iterator i;
string s;
while (cin >> s) {
    transform(s.begin(), s.end(), s.begin(), ::tolower);
words[s]++;
  }
for (i=words.begin(); i != words.end(); i++)
    cout << i->first << " " << i->second << endl;
return 0;

现在如何让它计算行频率,而不是字频率。每行由输入中的\\\
新行字符分隔。

Now how do I make it to count line frequency instead of word frequency. Each line is separated by '\n' new line character in the input.

推荐答案

如果要计算总行数,那么它很简单:

If you want to count the total lines, then its very simple:

 size_t countLine = 0;
 while(std::getline(std::cin, s)) countLine++;

但如果你真的想计算同一行的频率您的代码,替换

But if you really want to count frequency of same line, then in your code, replace

string s;

line s;

其中定义为: p>

where line is defined as:

struct line : std::string
{
    friend std::istream & operator >> (std::istream &in, line &ln) 
    {
        return std::getline(in, ln);
    }
};

或者,您可以使其通用:

Or, you can make it generic:

template<typename CharT, typename Traits = std::char_traits<CharT>, typename Allocator = std::allocator<CharT>>
struct basic_line : public std::basic_string<CharT, Traits, Allocator>
{
    friend std::basic_istream<CharT, Traits> & operator >> (std::basic_istream<CharT, Traits > &in, basic_line<CharT, Traits, Allocator> &ln) 
    {
        return std::getline(in, ln);
    }
};

然后定义这些typedef:

then define these typedefs:

typedef basic_line<char>    line;
typedef basic_line<wchar_t> wline;

这篇关于扩展程序以计算行频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆