function_object在for_each之后丢失了数据成员的值

时间:2012-02-19 19:46:58

标签: c++ stl

以下代码应存储密钥和值。最后,我想要所有值的总和。但是我的函数对象 sum 中的变量* sum_all *每次都包含“0”。发生了什么事?

// map
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;

struct Item {
    int count;
    double value;
};


class Sum {
public:
    Sum() {
        sum_all = 0.0;
    }
    // keys are stored as const in a map
    void operator()(pair<const string, Item>& pair) {
        cout << pair.first << "\n";
        cout << "Sum: " << pair.second.value << "\n";
        cout << "Middle: " << pair.second.value/pair.second.count << "\n";

        sum_all += pair.second.value;
    }
    double get_sum_all() {
        return sum_all;
    }
private:
    double sum_all;
};

int main() {
    map<string, Item> table;

    for (int i = 0; i < 3; i++) {
        string key;
        double value;
        cin >> key;
        cin >> value;

        // new item
        if (table.find(key) == table.end()) {
            Item item;
            item.count = 1;
            item.value = value;
            table[key] = item;
        } else {
            Item& item = table[key];
            item.count++;
            item.value += value;
        }
    }

    Sum sum;
    for_each(table.begin(), table.end(), sum);

    cout << "table.size() " << table.size() << "\n";
    cout << "sum.get_sum_all() " << sum.get_sum_all() << "\n";
    cout << "sum.get_sum_all()/table.size()" << sum.get_sum_all()/table.size() << "\n";


    return 0;
}

输入/输出示例:

[peter@donut chap_6]$ ./u3_map 
foo 1
bar 2
foo 1
bar
Sum: 2
Middle: 2
foo
Sum: 2
Middle: 1
table.size() 2
sum.get_sum_all() 0
sum.get_sum_all()/table.size()0

调试显示,sum_all被修改为在for_each期间应该修改。但是我无法设置观察点,或者gdb忽略了观察点。我认为构造函数被调用两次,但这似乎不会发生。我做错了什么? 感谢。

1 个答案:

答案 0 :(得分:3)

std::for_each将其仿函数参数按值,而不是按引用。原件未修改。你需要做这样的事情:

sum = for_each(table.begin(), table.end(), sum);