我编写了一个类来处理程序中的所有随机数生成。我正在尝试在该类中实现函数,这些函数采用向量或指向数组的指针并随机选择其中一个元素。我正在为这些函数使用模板,因此它们可以从包含任何类型的数组或向量中进行选择。
但是,在编译(MSVC 2012)时,两个模板函数都出现“错误 C3861:'double0to1': identifier not found”错误。double0To1 是该类的公共成员函数。
在 rng.h 中:
#ifndef RNG_H
#define RNG_H
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <vector>
class RNG
{
public:
RNG(int seedIn);
~RNG(void);
double double0To1();
int positiveIntLessThan(int upperBound);
template<class T> T* randomObjectInVector(std::vector<T*> vectorToChooseFrom);
template<class T> T* randomObjectInArray(T** arrayToChooseFrom, int size);
private:
int seed;
boost::random::uniform_real_distribution<double> *distribution0To1;
boost::mt19937 generator;
boost::random::variate_generator<boost::mt19937, boost::random::uniform_real_distribution<double>> *mersenne0To1;
};
template<class T> T* RNG::randomObjectInVector(std::vector<T*> vectorToChooseFrom)
{
double randNum=double0to1();
double step=1/vectorToChooseFrom.size();
int indexToTake=floor(randNum/step);
return vectorToChooseFrom[indexToTake];
}
template<class T> T* RNG::randomObjectInArray(T** arrayToChooseFrom, int size)
{
double randNum=double0to1();
double step=1/size;
int indexToTake=floor(randNum/step);
return &((*arrayToChooseFrom)[indexToTake]);
}
在 rng.cpp 中:
#include "stdafx.h"
#include "RNG.h"
RNG::RNG(int seedIn)
{
seed=seedIn;
generator.seed(seed);
distribution0To1=new boost::random::uniform_real_distribution<double>(0, 1);
mersenne0To1=new boost::random::variate_generator<boost::mt19937, boost::random::uniform_real_distribution<double> >(generator, *distribution0To1);
}
RNG::~RNG(void)
{
delete distribution0To1;
}
double RNG::double0To1()
{
return (*mersenne0To1)();
}
int RNG::positiveIntLessThan(int upperBound)
{
double randomValue=double0To1();
return int(upperBound*randomValue);
}