在程序设计实验用了一下类

  1 #include "stdafx.h"
  2 
  3 #include <iostream>
  4 #include <cstdlib>
  5 #include <cstring>
  6 #include <algorithm>
  7 using namespace std;
  8 
  9 #define EQUAL 0
 10 #define WORDLEN 200
 11 #define CHAR_COUNT 26
 12 
 13 struct word {
 14     char name[WORDLEN];
 15     int fre[CHAR_COUNT];
 16 };
 17 
 18 class dict {
 19     static const int DICTVOL = 100;
 20     word list[DICTVOL];
 21     int wordcount;
 22 public:
 23     dict();
 24     void addword(const char str[]);
 25     void search(const char req[]);
 26     void dictsort();
 27     friend void calfre(word & tar);
 28     friend bool frecmp(word & w1, word & w2);
 29 };
 30 
 31 
 32 void calfre(word & tar) //log the frequency of each char
 33 {
 34     for (int i = 0; i < CHAR_COUNT; i += 1)
 35         tar.fre[i] = 0;
 36     for (int i = 0; tar.name[i] != ''; i += 1) 
 37         tar.fre[tar.name[i] - 'a'] += 1;
 38 }
 39 bool frecmp(word &w1, word &w2) 
 40 {
 41     for (int i = 0; i < CHAR_COUNT; i += 1)
 42     {
 43         if (w1.fre[i] != w2.fre[i])
 44             return false;
 45     }
 46     return true;
 47 }
 48 bool dictcmp(word & a, word & b)
 49 {
 50     if (strcmp(a.name, b.name) < 0) return true;
 51     else return false;
 52 }
 53 dict::dict()
 54 {
 55     memset(list,0,sizeof(list));
 56     wordcount = 0;
 57 }
 58 void dict::addword(const char str[])
 59 {
 60     strcpy_s(list[wordcount].name, str);
 61     calfre(list[wordcount]);
 62     wordcount += 1;
 63 }
 64 void dict::search(const char req[])
 65 {
 66     bool found = false;
 67     word temp;
 68     strcpy_s(temp.name, req);
 69     calfre(temp);
 70 
 71     for (int i = 0; i < wordcount; i += 1)
 72     {
 73         if (frecmp(list[i], temp) == true)
 74         {
 75             cout << list[i].name << endl;
 76             found = true;
 77         }
 78     }
 79     if (found == false)
 80         cout << "NOT A VALID WORD" << endl;
 81     cout << "******" << endl;
 82 }
 83 void dict::dictsort()
 84 {
 85     word temp[DICTVOL];
 86     for (int i = 0; i < wordcount; i += 1)
 87         temp[i] = list[i];
 88     sort(temp, temp + wordcount, dictcmp);
 89     for (int i = 0; i < wordcount; i += 1)
 90         list[i] = temp[i];
 91 }
 92 
 93 int main()
 94 {
 95     dict d;
 96     char temp[WORDLEN];
 97     cin >> temp;
 98     while (strcmp(temp, "XXXXXX") != EQUAL)
 99     {
100         d.addword(temp);
101         cin >> temp;
102     }
103     d.dictsort();
104     cin >> temp;
105     while (strcmp(temp, "XXXXXX") != EQUAL)
106     {
107         d.search(temp);
108         cin >> temp;
109     }
110     return 0;
111 }
原文地址:https://www.cnblogs.com/KakagouLT/p/8537920.html