gpt4 book ai didi

c++ - 在类的无序映射中使用滚动累加器

转载 作者:行者123 更新时间:2023-11-30 03:40:19 24 4
gpt4 key购买 nike

我正在尝试使用无序映射来保存类中的滚动累加器。

首先让我展示一下什么是有效的。这是一个类中的累加器,它在没有 map 的情况下也能按预期工作。注意累加器需要在初始化列表中进行初始化。

#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>

namespace nmbstacc = boost::accumulators;
typedef nmbstacc::accumulator_set<double, nmbstacc::stats<nmbstacc::tag::rolling_mean >> MACC;

class RollMean {

public:
MACC m_acc;
RollMean(void) : m_acc(nmbstacc::tag::rolling_window::window_size = 3) {}
};

int main()
{
RollMean obj;
obj.m_acc(0.5);
obj.m_acc(1.5);
obj.m_acc(2.5);
obj.m_acc(3.5);

std::cout << "roll_mean: " << nmbstacc::rolling_mean(obj.m_acc) << std::endl;

std::getchar();
return 0;
}

但是,我需要的是一个无序映射来将这些累加器保存在一个类中,但似乎无法弄清楚如何编译以下程序。我不确定如何在不先初始化滚动累加器的情况下声明 mainmap 容器。

#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>
#include <unordered_map>

namespace nmbstacc = boost::accumulators;
typedef nmbstacc::accumulator_set<double, nmbstacc::stats<nmbstacc::tag::rolling_mean >> MACC;

class RollMean {

public:
MACC m_acc;
std::unordered_map<std::string, MACC> mainmap;
RollMean(std::string name) : m_acc(nmbstacc::tag::rolling_window::window_size = 3) {
mainmap.emplace(name, m_acc);
}
};

int main()
{
RollMean obj("a");
obj.mainmap["a"](1.0);

std::cout << "roll_mean: " << nmbstacc::rolling_mean(obj.mainmap["a"]) << std::endl;

std::getchar();
return 0;
}

我收到以下错误:

错误 C2679 二进制“[”:未找到接受类型为“boost::parameter::keyword”的右手操作数的运算符(或没有可接受的转换)

谢谢。

最佳答案

就像@jv_ 暗示的那样,map[key] 是一个变异操作,如果不存在则插入一个默认构造的元素。

但是,您的元素类型没有默认构造函数。因此,您不能使用该运算符。

如果你使用 obj.mainmap.at("a") 而不是 obj.mainmap["a"],你会得到一个丢失键的异常相反。

Live On Coliru

#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>
#include <unordered_map>

namespace nmbstacc = boost::accumulators;
typedef nmbstacc::accumulator_set<double, nmbstacc::stats<nmbstacc::tag::rolling_mean> > MACC;

class RollMean {

public:
MACC m_acc;
std::unordered_map<std::string, MACC> mainmap;
RollMean(std::string name) : m_acc(nmbstacc::tag::rolling_window::window_size = 3) { mainmap.emplace(name, m_acc); }
};

int main() {
RollMean obj("a");
obj.mainmap.at("a")(1.0);

std::cout << "roll_mean: " << nmbstacc::rolling_mean(obj.mainmap.at("a")) << std::endl;
}

打印:

roll_mean: 1

关于c++ - 在类的无序映射中使用滚动累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com