Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <iterator>
  5. #include <vector>
  6. #include <functional>
  7.  
  8.  
  9. /*
  10. * Generic implementation to erase elements by Callback
  11. * It iterates over all the elements and for every element it executes
  12. * the callback, if it returns the true then it will delete
  13. * that entry and move to next.
  14. */
  15. template<typename K, typename V>
  16. int erase_if(std::map<K, V> & mapOfElemen, bool(* functor)(V))
  17. {
  18. bool totalDeletedElements = 0;
  19. auto it = mapOfElemen.begin();
  20. // Iterate through the map
  21. while(it != mapOfElemen.end())
  22. {
  23. // Check if value of this entry matches with given value
  24. if(functor(it->second))
  25. {
  26. totalDeletedElements++;
  27. // Erase the current element, erase() will return the
  28. // next iterator. So, don't need to increment
  29. it = mapOfElemen.erase(it);
  30. }
  31. else
  32. {
  33. // Go to next entry in map
  34. it++;
  35. }
  36. }
  37. return totalDeletedElements;
  38. }
  39.  
  40. bool isODD(int val)
  41. {
  42. if(val % 2 == 1)
  43. return true;
  44. else
  45. return false;
  46. }
  47. int main() {
  48.  
  49. // Map of string & int i.e. words as key & there
  50. // occurrence count as values
  51. std::map<std::string, int> wordMap = {
  52. { "is", 6 },
  53. { "the", 5 },
  54. { "hat", 9 },
  55. { "at", 6 }
  56. };
  57.  
  58. std::cout << "Map Entries Before Deletion" << std::endl;
  59. // Print the map elements
  60. for (auto elem : wordMap)
  61. std::cout << elem.first << " :: " << elem.second << std::endl;
  62.  
  63. // Erase all the elements whose value is ODD
  64. int deletedCount = erase_if(wordMap, &isODD);
  65.  
  66. std::cout<<"Total elements deleted = "<<deletedCount<<std::endl;
  67.  
  68. std::cout << "Map Entries After Deletion" << std::endl;
  69. // Print the map elements
  70. for (auto elem : wordMap)
  71. std::cout << elem.first << " :: " << elem.second << std::endl;
  72.  
  73.  
  74. return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement