template class implementation errors
Aug 10, 2017 at 2:30am UTC
Below are my codes to generate random numbers based on user-defined weighting values. It all works, until I tried to make the type of data become any types, e.g. double, float. I have little experience implement them in practice, only read about them on textbooks. Can anyone helps me fix it?
Thanks,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
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();
}
Aug 10, 2017 at 3:19am UTC
Aug 10, 2017 at 2:24pm UTC
Thank you. I think I know how to fix it now.
Topic archived. No new replies allowed.