Guest User

Untitled

a guest
Apr 28th, 2012
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. function_object lost value of data member after for_each
  2. // map
  3. #include <iostream>
  4. #include <string>
  5. #include <map>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. struct Item {
  10. int count;
  11. double value;
  12. };
  13.  
  14.  
  15. class Sum {
  16. public:
  17. Sum() {
  18. sum_all = 0.0;
  19. }
  20. // keys are stored as const in a map
  21. void operator()(pair<const string, Item>& pair) {
  22. cout << pair.first << "n";
  23. cout << "Sum: " << pair.second.value << "n";
  24. cout << "Middle: " << pair.second.value/pair.second.count << "n";
  25.  
  26. sum_all += pair.second.value;
  27. }
  28. double get_sum_all() {
  29. return sum_all;
  30. }
  31. private:
  32. double sum_all;
  33. };
  34.  
  35. int main() {
  36. map<string, Item> table;
  37.  
  38. for (int i = 0; i < 3; i++) {
  39. string key;
  40. double value;
  41. cin >> key;
  42. cin >> value;
  43.  
  44. // new item
  45. if (table.find(key) == table.end()) {
  46. Item item;
  47. item.count = 1;
  48. item.value = value;
  49. table[key] = item;
  50. } else {
  51. Item& item = table[key];
  52. item.count++;
  53. item.value += value;
  54. }
  55. }
  56.  
  57. Sum sum;
  58. for_each(table.begin(), table.end(), sum);
  59.  
  60. cout << "table.size() " << table.size() << "n";
  61. cout << "sum.get_sum_all() " << sum.get_sum_all() << "n";
  62. cout << "sum.get_sum_all()/table.size()" << sum.get_sum_all()/table.size() << "n";
  63.  
  64.  
  65. return 0;
  66. }
  67.  
  68. [peter@donut chap_6]$ ./u3_map
  69. foo 1
  70. bar 2
  71. foo 1
  72. bar
  73. Sum: 2
  74. Middle: 2
  75. foo
  76. Sum: 2
  77. Middle: 1
  78. table.size() 2
  79. sum.get_sum_all() 0
  80. sum.get_sum_all()/table.size()0
  81.  
  82. sum = for_each(table.begin(), table.end(), sum);
Advertisement
Add Comment
Please, Sign In to add comment