Qt创建不重复随机数

来源:互联网 发布:软件开发相关书籍 编辑:程序博客网 时间:2024/05/22 07:06

该代码创建一个随机数的类。

构造函数有两个:(1)参数为一个整形数,如传入300,则产生0~299的随机数,其中随机数不重复。(2)参数为Qlist<int>,根据这个list直接初始化。


//头文件

#ifndef RAND_NUM
#define RAND_NUM
#include <QList>
class RandNum
{
    public:
        RandNum(int nimg);
        RandNum(QList<int> ilist);
        ~RandNum();
        int  getRandNum(int x);
        void showRandNum(void) const;
        int  getImgNum(void);
protected:
 private:
        QList<int> intList;
        int  nImg;
};
#endif // RAND_NUM

//.cpp文件

#include <QDebug>
#include <QApplication>
#include "mainwindow.h"
#include <QTime>
#include <rand_num.h>
RandNum::RandNum(int nimg)
{
    this->nImg=nimg;
    int   i=0, m=0;
    QTime time;
    for(i=0;;)
    {
        int     randn;
        time    = QTime::currentTime();
        qsrand(time.msec()*qrand()*qrand()*qrand()*qrand()*qrand()*qrand());
        randn   = qrand()%nImg;
        m=0;
        while(m<i && intList.at(m)!=randn) m++;
        if(m==i)            { intList.append(randn); i++;}
        else if(i==nImg)    break;
        else                continue;
    }
}
RandNum::RandNum(QList<int> ilist)
{
    this->nImg = intList.count();
    this->intList = ilist;
}
RandNum::~RandNum(){}
int  RandNum::getRandNum(int x)
{
    if (x>=intList.count()){
        qDebug()<<"exceed intList count!"<<"x:"<<x<<";count:"<<intList.count();
        return -1;
    }else{
        return this->intList.at(x);
    }
}
 void RandNum::showRandNum() const
{
    qDebug()<<"=====randNumber show begin========";
    qDebug()<<"intList.count():"<<intList.count();
    for(int i=0; i<this->intList.count(); i++) {
        qDebug()<<i<< this->intList.at(i);
    }
    qDebug()<<"=====randNumber show end==========\n";
}
int  RandNum::getImgNum()       { return intList.count(); }

0 0
原创粉丝点击