繁体   English   中英

模板类实现错误

[英]template class implementation errors

下面是我的代码,用于根据用户定义的加权值生成随机数。 一切正常,直到我试图使数据类型成为任何类型,例如double,float。 我几乎没有在实践中实施它们的经验,只在教科书中阅读了它们。 谁能帮我解决这个问题?

谢谢,

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用作模板化类型。

#include<unordered_map>
#include<iostream>
#include<math.h>
using namespace std;
template<typename T1,typename T2>
class WeightedRandom{
public:
    void setWeight(T1 i,T2 val)
    {
        m[i]=val;
        total+=val;
    }
    void generator()
    {
        T2 val= (T2) fmod(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:
    unordered_map<T1,T2> m;
    unordered_map<T1,T2> res; // object-count
    T2 total=0;
};

int main(int argc, const char * argv[])
{
    WeightedRandom<int,double> WR;
    WR.setWeight(1, 5.01);
    WR.setWeight(2, 19.99);
    WR.setWeight(3, 50.01);
    WR.setWeight(4, 19.99);
    WR.setWeight(5, 10.00);
    int n=10000;
    for (int i=0;i<n;++i)
    {
        WR.generator();
    }
    WR.print();
}

fmod需要一个double,因此,如果它是int或float,它将被提升为double,结果将被回退,或者如果为double,则强制转换将不执行任何操作。 您可能要考虑添加一些检查,以确保只能使用double / float或char / short / int / long,因为用户可能会使用某种类别的权重,这不会太有意义:

...
class WeightedRandom{
    static_assert(!is_same<T,bool>(),"type can't be a bool");
    static_assert(is_arithmetic<T>(),"type needs to be an arithmetic");
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM