下面是我的代码,用于根据用户定义的权重值生成随机数。这一切都有效,直到我试图让数据类型成为任何类型,例如双,浮动。我没有什么经验在实践中实施,只能在教科书上阅读。任何人都可以帮助我解决它吗?模板类执行错误
感谢,
class WeightedRandom
{
public:
template <class T1,class T2>
void setWeight(T1 i,T2 val)
{
m[i]=val;
total+=val;
}
void generator()
{
int val=rand()%total;
for (auto a:m)
{
if (val<a.second)
{
res[a.first]++;
break;
}
val-=a.second;
}
}
void print()
{
for (auto a:res)
{
cout<<a.first<<" "<<a.second<<endl;
}
}
private:
template <class T1,class T2>
unordered_map<T1,T2> m;
template <class T3,class T4>
unordered_map<T3,T4> res; // object-count
int total=0;
};
int main(int argc, const char * argv[])
{
WeightedRandom WR;
WR.setWeight(1, 5);
WR.setWeight(2, 20);
WR.setWeight(3, 50);
WR.setWeight(4, 20);
WR.setWeight(5, 10);
int n=10000;
for (int i=0;i<n;++i)
{
WR.generator();
}
WR.print();
}
什么是错误?顺便说一句,在'total + = val;''val'是T2的时候,你有'int total'。 – Serge
是原来的地方,现在所有的模板都是int吗? –