fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <algorithm>
  4.  
  5. struct Snode
  6. {
  7. char data;
  8. int count;
  9. };
  10.  
  11. class set
  12. {
  13. private:
  14. std::list<Snode> nodes;
  15.  
  16. auto findValue(char value)
  17. {
  18. return std::find_if(nodes.begin(), nodes.end(),
  19. [=](const Snode &n){ return (n.data == value); }
  20. );
  21. }
  22.  
  23. public:
  24. bool isAvailable(char value)
  25. {
  26. return (find(value) != nullptr);
  27. }
  28.  
  29. Snode* find(char value)
  30. {
  31. auto iter = findValue(value);
  32. if (iter != nodes.end())
  33. return &*iter;
  34. return nullptr;
  35. }
  36.  
  37. bool isFirst(char value)
  38. {
  39. return ((!nodes.empty()) && (nodes.front().data == value));
  40. }
  41.  
  42. bool isLast(char value)
  43. {
  44. return ((!nodes.empty()) && (nodes.back().data == value));
  45. }
  46.  
  47. void display()
  48. {
  49. for (auto &n : nodes)
  50. std::cout << n.data << " " << n.count << std::endl;
  51. }
  52.  
  53. void insert(char value)
  54. {
  55. Snode *temp = find(value);
  56. if (temp)
  57. temp->count += 1;
  58. else
  59. nodes.push_back(Snode{value, 1});
  60. }
  61.  
  62. int count(char value)
  63. {
  64. Snode *temp = find(value);
  65. return (temp) ? temp->count : 0;
  66. }
  67.  
  68. void deleteFirst()
  69. {
  70. if (!nodes.empty())
  71. nodes.pop_front();
  72. }
  73.  
  74. void deleteLast()
  75. {
  76. if (!nodes.empty())
  77. nodes.pop_back();
  78. }
  79.  
  80. void remove(char value)
  81. {
  82. auto iter = findValue(value);
  83. if (iter != nodes.end())
  84. {
  85. if (iter->count > 1)
  86. iter->count -= 1;
  87. else
  88. nodes.erase(iter);
  89. }
  90. }
  91. };
  92.  
  93. int main()
  94. {
  95. //defining a mySet as a "set" type
  96. set mySet;
  97.  
  98. //adding values to create nodes
  99. mySet.insert('c');
  100. mySet.insert('a');
  101. mySet.insert('a');
  102. mySet.insert('c');
  103. mySet.insert('c');
  104.  
  105. set myCopiedSet = mySet; // make a copy of the list
  106.  
  107. //adding more values to create nodes
  108. myCopiedSet.insert('a');
  109. myCopiedSet.insert('b');
  110. myCopiedSet.insert('b');
  111. myCopiedSet.insert('c');
  112.  
  113. // another test
  114. set myTestSet;
  115. myTestSet.insert('c');
  116. myTestSet.insert('c');
  117. myTestSet.insert('j');
  118. myTestSet.insert('j');
  119. myTestSet.insert('j');
  120. myTestSet.insert('r');
  121.  
  122. //displaying nodes through "value count" format
  123. std::cout << "original:" << std::endl;
  124. mySet.display();
  125. std::cout << "copy:" << std::endl;
  126. myCopiedSet.display();
  127. std::cout << "test:" << std::endl;
  128. myTestSet.display();
  129.  
  130. return 0;
  131. }
Success #stdin #stdout 0s 4180KB
stdin
Standard input is empty
stdout
original:
c 3
a 2
copy:
c 4
a 3
b 2
test:
c 2
j 3
r 1