地图中的增量元组

Increment tuples in a map

我有以下 class 我正在使用的成员:

std::map<std::string, std::tuple<double, double, int>> errors;

我们的想法是循环遍历一系列 bin,每个 bin 都有一个 std::string 名称,以及与之关联的 3 个值。

我们想在误差超过某个阈值时将每家银行添加到地图中,并对三个值求和。

我目前有:

 std::map<std::string, std::tuple<double, double, int>> errors;

std::string binname = "BIN1";
double mean = 5.5;
double stddev = 12.3;
int count = 1;

errors.emplace(std::piecewise_construct, std::forward_as_tuple(binname),
std::forward_as_tuple(mean, stddev, count));

将新银行添加到列表中效果很好。但是当银行已经有来自该银行的条目时,我需要一些东西来对元组求和。即类似于:

if(errors.find(binname))
{
    errors.find(binname).first += mean;
    errors.find(binname).second += stddev;
    errors.find(binname).third += 1;
}

或类似的东西。我想我可以拉元组单独添加每个元素并创建一个新条目。这是最好的方法吗?我不是 100% 设置结构本身,但最好保持这样。

在 C++17 中,使用 Structured binding,你可以无条件地做:

auto& [err_mean, err_stddev, err_count] = errors[binname];
err_mean += mean;
err_stddev += stddev;
err_count += 1;
如果不存在,

errors[binname] 将创建默认条目 ({0., 0., 0})。

对于 c++17 之前的版本,

auto& tup = errors[binname];
std::get<0>(tup) += mean;
std::get<1>(tup) += stddev;
std::get<2>(tup) += 1;