fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. const int maxListSize = 50;
  5.  
  6. template<class T>
  7. class List
  8. {
  9. private:
  10. int numberOfElements;
  11. int currentPosition;
  12. T data[maxListSize];
  13. public:
  14. List()
  15. {
  16. numberOfElements = 0;
  17. currentPosition = -1;
  18. }
  19. void insert(T element)
  20. {
  21. if (numberOfElements >= maxListSize)
  22. {
  23. return;
  24. }
  25. data[numberOfElements] = element;
  26. numberOfElements++;
  27. }
  28.  
  29. bool first(T &element)
  30. {
  31. if (numberOfElements == 0)
  32. {
  33. return false;
  34. }
  35. else
  36. {
  37. currentPosition = 0;
  38. element = data[currentPosition];
  39. return true;
  40. }
  41. }
  42.  
  43. bool next(T &element)
  44. {
  45. if (currentPosition < 0)
  46. {
  47. return false;
  48. }
  49. if (currentPosition >= numberOfElements - 1)
  50. {
  51. return false;
  52. }
  53. currentPosition++;
  54. element = data[currentPosition];
  55. return true;
  56. }
  57. };
  58.  
  59. using WordPair = std::pair<std::string, int>;
  60. using WordList = List<WordPair*>;
  61.  
  62. void incrementCount(WordList &wl, const std::string& s)
  63. {
  64. WordPair* item = nullptr;
  65. if (wl.first(item))
  66. {
  67. if (item->first == s)
  68. {
  69. ++(item->second);
  70. return;
  71. }
  72. while (wl.next(item))
  73. {
  74. if (item->first == s)
  75. {
  76. ++(item->second);
  77. return;
  78. }
  79. }
  80. }
  81. wl.insert(new WordPair { s, 1 });
  82. }
  83.  
  84. void printList(WordList &wl)
  85. {
  86. WordPair *item = nullptr;
  87. if (wl.first(item))
  88. {
  89. std::cout << item->first << " : " << item->second << "\n";
  90. while (wl.next(item))
  91. {
  92. std::cout << item->first << " : " << item->second << "\n";
  93. }
  94. }
  95. }
  96.  
  97. int main()
  98. {
  99. std::string words[10] = { "one", "two", "three", "four", "one",
  100. "two", "three", "two", "three", "three" };
  101. WordList wl;
  102. for (int i = 0; i < 10; ++i)
  103. {
  104. incrementCount(wl, words[i]);
  105. }
  106. printList(wl);
  107. }
Success #stdin #stdout 0s 4648KB
stdin
Standard input is empty
stdout
one : 2
two : 3
three : 4
four : 1