Extending a program to count line frequency

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.

Answers


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;

with

line s;

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);
    }
};

then define these typedefs:

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

Need Your Help

Message/chat system with a negative margin for each message

css design chat messaging

I'm trying to transfer the following mockup into working dynamic code but I'm having a few problems right now.

How to debug “Xcode CodeSign error: The entitlements file Entitlements.plist is missing” in Xcode 4?

iphone ios xcode xcode4 code-signing

Xcode throws this error when I try to CMD+I (Profile) an app on the device. Running is fine. Just profiling doesn't work and gives this error.

Parsing XML data with php

php xml parsing

I am trying to pull text from a single element in an xml file, i was able to pull the entire file but i really only need a couple of lines from the file...