簡體   English   中英

C ++ TR1:在const方法中使用均勻分布生成隨機數的正確方法是什么?

[英]C++ TR1: What is the proper way to use a uniform distribution to generate a random number in a const method?

我有一個簡單的const方法,想要生成一個隨機數

int Object::const_method() const {
    std::tr1::uniform_int<int> uni(0,100);
    // do some calculation
   return result;
}

這會導致您的標准(如果被模板化)const違反錯誤

/usr/lib/gcc/x86_64-unknown-linux-gnu/4.5.1/../../../../include/c++/4.5.1/tr1/random.tcc:910:4:錯誤:將'const std :: tr1 :: mersenne_twister'作為'result_type std :: tr1 :: mersenne_twister <_UIntType,__w,__n,__m,__r,__a,__u,__s,__b,__t,__c, __l> :: operator()()[with _UIntType = long unsigned int,int __w = 32,int __n = 624,int __m = 397,int __r = 31,_UIntType __a = 2567483615ul,int __u = 11,int __s = 7,_UIntType __b = 2636928640ul,int __t = 15,_UIntType __c = 4022730752ul,int __l = 18,result_type = long unsigned int]'丟棄限定符

這是可行的沒有const_castthis

使您的mersenne_twister對象在您的類中可變。 沒有看到您所有的代碼(尤其是do_something部分),我們無法確定,但是我猜想您在merseene_twister類型的類中有一個對象,您正在使用的對象本身不是const函數。 這會在您的類中引起錯誤,因為您的const函數正在merseen_twister上調用一個可能會更改它的函數,從而違反了const簽名。

// I'm using this as an example.  Yours may differ
typedef std::mersenne_twister<unsigned int, 32, 624, 
    397, 31, 0x9908b0df, 11, 7, 0x9d2c5680, 
    15, 0xefc60000, 18> MerTwister;

class Object 
{
    public:

    int Object::const_method() const 
    {
       std::tr1::uniform_int<int> uni(0,100);

       // do some calculation using the MerTwister object
       return result;
    }


    private:
    mutable MerTwister twister;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM