Search code examples
c++sortingword-count

Word Count with Sorting C++


This is a question I have for my Data Structure class. I have completely no idea in dealing with it, can anyone give some hints please?

  1. How to stop the program and ensure the output can be out correctly?
  2. Whether I have to deal with the mapping?

the question paper I had from the professor

The following is my coding example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s [100];

    for (int i = 0; i < 100; i++) {
        cin >> s[i];
        s[i] = Sort(s[i], s[i+1]);
    }


    //check the number of time the words repeatcout the answer
    for (int i = 0; i < 100; i++) {
        cout << s[i] << count (s[i],s[i+1]) <<endl;
    }
    return 0;
}


string Sort(string current, string next ) {
    if (current > next) {
        string temp = current;
        current = next;
        next = temp;
    }
    else {
        return current;
    }
}

int count(string word, string Nextword) {
    int count;
    if (word == Nextword) {
        count++;
    }
    else {
        return count;
    }
}

Solution

  • std::map can do sorting and counting at the same time for you:

    #include <map>
    #include <iostream>
    using std::cin;
    using std::cout;
    using std::endl;
    using std::string;
    
    int main() {
      std::map<string,size_t> wordcount;
      for(string word;cin>>word;++wordcount[word]);
      for(auto it=wordcount.begin();it!=wordcount.end();++it)
        cout << it->first << " " << it->second << endl;
    }
    
    echo -ne "Computer system\ncomputer design\nalgorithm design and analysis\nquantum computer\ncomputer science department" | ./a.out
    Computer 1
    algorithm 1
    analysis 1
    and 1
    computer 3
    department 1
    design 2
    quantum 1
    science 1
    system 1