Write a program that reads a list of words. Then, the program outputs those words and their frequencies. The input begins with an integer indicating the number of words that follow. Assume that the list will always contain less than 20 words. Ex: If the input is: 5 hey hi Mark hi mark the output is: hey 1 hi 2 Mark 1 hi 2 mark 1

Respuesta :

Sample Output

5 hey hi Mark hi mark

hey 1

hi 2

Mark 1

hi 2

mark 1

Explanation

#include <iostream>

#include <vector>

#include <string>

using namespace std;

int main() {

   /* Type you code here. */

   //Define a vector

   //to store the words.

   vector <string> words_list;

   //Define a vector to store

   //the frequencies of the words.

   vector <int> frequency_list;

   

   //Declare the

   //required variables.

   string curr_word;

   int num_words;

   //Read and store the total

   //number of words to be read.

   cin >> num_words;

   //Run the loop to read

   //and store the words

   for(int i=0; i<num_words; i++)

   {

       //Read and store

       //the current word.

       cin >> curr_word;

       

       //Push the current

       //word into the vector.

       words_list.push_back(curr_word);

   }

   //Run the loop to find the

   //frequency of each word.

   for(int i=0; i<num_words; i++)

   {

       //Read the word present at

       //the i'th position in the vector.

       curr_word = words_list.at(i);

       int count = 0;

       //Run the loop to find the

       //frequency of the current word.

       for(int j=0; j<num_words; j++)

       {

           if(words_list.at(j) == curr_word)

           {

               count++;

           }

       }

       //Insert the frequency

       //of the current word.

       frequency_list.push_back(count);

   }

   //Run the loop to display

   //the word and its frequency.

   for(int i=0; i<num_words; i++)

   {

       cout << words_list.at(i)

       << " " << frequency_list.at(i)

       << endl;

   }

   //Return from the

   //main() function.

   return 0;

}