嗨堆棧交換專家,Boost:將指針存儲在向量中的分佈
我想收集指向不同的統計分佈提供的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);
,然後迭代向量和應用功能等來解除引用指針。 但由於這是不是我真的不知道如何指針存儲在一個地方的情況?因此,我的問題是,如果有一種方法可以將指向不同模板類的指針存儲在一個變量/列表/矢量中(可以像std :: vector一樣方便地處理)。
注意,例如Boost pdf密度函數可以應用於解除引用的指針,而不管特定的類型(因此將它們存儲在一個向量中在某些情況下有意義)。
////////////////////////////////////////////// ////////////////////////////
我玩過各種不錯的答案,最後決定堅持提升: :與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;
}
我看到的唯一的缺點是需要分配的類型必須明確指定(在變型),所以它可能是提振::任何增加更多的自由。
感謝您的幫助很大!
Hank
添加了更多詳細示例的鏈接 – sehe