gpt4 book ai didi

c++ - Boost:在 vector 中存储指向分布的指针

转载 作者:太空狗 更新时间:2023-10-29 21:21:23 28 4
gpt4 key购买 nike

您好 Stack Exchange 专家,

我试图在一个 vector 中收集指向 Boost 提供的不同统计分布的指针。如果分布是从一个(虚拟)父类派生的,我可以写类似的东西

std::vector<Parent> v;

boost::math::normal_distribution<double> n;
boost::math::students_t_distribution<float> t(4);

boost::math::normal_distribution<double> *p1 = new boost::math::normal_distribution<double>(n);
boost::math::students_t_distribution<float> *p2 = new boost::math::students_t_distribution<float>(t);
v.push_back(p1);
v.push_back(p2);

然后遍历 vector 并将函数等应用于取消引用的指针。但由于情况并非如此,我真的不知道如何将指针存储在一个地方?

所以我的问题是,是否有一种方法可以将指向不同模板类的指针存储在一个变量/列表/vector 中...(例如,可以像 std::vector 一样方便地处理)。

请注意,例如 Boost pdf 密度函数可以应用于取消引用的指针,而不管具体类型如何(因此在某些情况下将它们存储在一个 vector 中是有意义的)。

//////////////////////////////////////////////////////////////////////

我尝试了不同的(不错的)答案,最后决定坚持使用 boost::variant 和 boost::static_visitor。下面是一个完整的应用程序,它执行我在原始问题中概述的内容:

#include <boost/math/distributions.hpp>
#include <boost/variant.hpp>
#include <vector>
#include <iostream>

//template based visitor to invoke the cdf function on the distribution
class cdf_visitor_generic : public boost::static_visitor<double>
{
public:

//constructor to handle input arguments
cdf_visitor_generic(const double &x) : _x(x) {}

template <typename T>
double operator()(T &operand) const {
return(boost::math::cdf(operand,_x));
}

private:
double _x;
};

//shorten typing
typedef boost::variant< boost::math::normal_distribution<double>, boost::math::students_t_distribution<double> > Distribution;

int main (int, char*[])
{
//example distributions
boost::math::normal_distribution<double> s;
boost::math::students_t_distribution<double> t(1);

//build a variant
Distribution v = t;

//example value for evaluation
double x = 1.96;

//evaluation at one point
double y = boost::apply_visitor( cdf_visitor_generic(x),v);
std::cout << y << std::endl;


//build a vector and apply to all elements of it:
std::vector<Distribution> vec_v;

vec_v.push_back(s);
vec_v.push_back(t);


for (std::vector<Distribution>::const_iterator iter = vec_v.begin(); iter != vec_v.end(); ++iter){

//apply cdf to dereferenced iterator
double test = boost::apply_visitor( cdf_visitor_generic(x), *iter);
std::cout << test << std::endl;
}
return 0;
}

我看到的唯一缺点是需要明确指定分发类型(在变体中),因此 boost::any 可能会增加更多自由度。

感谢您的大力帮助!

汉克

最佳答案

您可以使用变体:

std::vector<boost::variant<
boost::math::normal_distribution<double>,
boost::math::students_t_distribution<float>
> > v;

boost::math::normal_distribution<double> n;
boost::math::students_t_distribution<float> t(4);

v.push_back(n);
v.push_back(t);

我有几个答案展示了如何“多态”地使用这些元素(虽然多态是通过静态编译类型切换,而不是 vtable 调度)。我会尽快添加一两个链接。

一些链接的答案显示了类型删除的“手动”方法

<子>附言。我也应该提到 boost::any,但我不喜欢它有几个原因。我不会为此目的推荐它。

关于c++ - Boost:在 vector 中存储指向分布的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22614133/

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