template class implementation errors

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();
  }
1
2
3
4
5
6
7
8
9
10
template < typename T1, typename T2 > class WeightedRandom
{
    public:
        void setWeight( T1 i, T2 val ) ;  
        // ...

    private:
        std::unordered_map<T1,T2> m ;
        // etc.  
};


Note: The standard library has a discrete distribution (weighted probabilities).
http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
Thank you. I think I know how to fix it now.
Topic archived. No new replies allowed.