本文整理汇总了C++中qrand函数的典型用法代码示例。如果您正苦于以下问题:C++ qrand函数的具体用法?C++ qrand怎么用?C++ qrand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了qrand函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: QImage
//.........这里部分代码省略.........
unsigned int t_index = x + ((y-1)*m_image_ptr->width());
unsigned int t_subobject_index =
pixel_subobject_nr[t_index];
while(subobjects[t_subobject_index].parent_subobject != 0){
t_subobject_index =
subobjects[t_subobject_index].parent_subobject;
}
connected_subobjects.append(t_subobject_index);
}
if (rt){
unsigned int rt_index = (x+1) +
((y-1)*m_image_ptr->width());
unsigned int rt_subobject_index =
pixel_subobject_nr[rt_index];
while(subobjects[rt_subobject_index].parent_subobject != 0){
rt_subobject_index =
subobjects[rt_subobject_index].parent_subobject;
}
connected_subobjects.append(rt_subobject_index);
}
if (l){
unsigned int l_index = (x-1) + (y*m_image_ptr->width());
unsigned int l_subobject_index =
pixel_subobject_nr[l_index];
while(subobjects[l_subobject_index].parent_subobject != 0){
l_subobject_index =
subobjects[l_subobject_index].parent_subobject;
}
connected_subobjects.append(l_subobject_index);
}
//If there are linked subobjects make connection
if (!connected_subobjects.isEmpty()){
//find subobject whit lowest index
qSort(connected_subobjects);
//add this subobject to bigger object
subobjects.last().parent_subobject =
connected_subobjects.first();
subobjects.last().pixels = 0;
subobjects[connected_subobjects.first()].pixels++;
//add other connected sub_objects to bigger object
for (int i=1; i<connected_subobjects.size(); i++){
//prevent adding subobjects to itself
if (connected_subobjects[i] !=
connected_subobjects.first()){
//Add subobject
subobjects[connected_subobjects[i]].parent_subobject
= connected_subobjects.first();
subobjects[connected_subobjects.first()].pixels +=
subobjects[connected_subobjects[i]].pixels;
subobjects[connected_subobjects[i]].pixels = 0;
}
}
}
}
pixel_subobject_nr.append(subobjects.size()-1);
}
}
//Init color lookup table
QList<QRgb> color_table;
//Add black for objects with to few pixels
color_table.append(0);
//Fill the color lookup table
for (int i=1; i<subobjects.size(); i++){
//generate new color
if (subobjects[i].parent_subobject == 0){
//check object size
if (subobjects[i].pixels > m_minWeightValue){
int r = qrand()%255;
int g = qrand()%255;
int b = qrand()%255;
QColor new_color(r,g,b);
color_table.append(new_color.rgb());
} else {
color_table.append(0);
}
} else {
color_table.append(color_table[subobjects[i].parent_subobject]);
}
}
//Make new image
for (int y=0; y < m_image_ptr->height(); y++){
for (int x=0; x < m_image_ptr->width(); x++){
m_image.setPixel(x,y, color_table[pixel_subobject_nr[x +
y*m_image_ptr->width()]]);
}
}
}
示例2: changeVerificationCodeT
void MusicUserRecordWidget::changeVerificationCodeT()
{
ui->verificationCode->setText(QString::number(qrand()).leftJustified(5, '0'));
}
示例3: QObject
Post::Post(QObject *parent) : QObject(parent), d_ptr(new PostPrivate(this))
{
Q_D(Post);
ins = this;
setObjectName("Post");
auto avProcess = [this](QNetworkReply *reply){
Q_D(Post);
Task &task = d->queue.head();
switch (task.state){
case None:{
QString api("http://interface.%1/dmpost");
api = api.arg(Utils::customUrl(Utils::Bilibili));
task.request.setUrl(api);
task.request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
const Comment &c = task.comment;
QUrlQuery params;
params.addQueryItem("cid", QFileInfo(task.target->source).baseName());
params.addQueryItem("date", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
params.addQueryItem("pool", "0");
params.addQueryItem("playTime", QString::number(c.time / 1000.0, 'f', 4));
params.addQueryItem("color", QString::number(c.color));
params.addQueryItem("fontsize", QString::number(c.font));
params.addQueryItem("message", c.string);
params.addQueryItem("rnd", QString::number(qrand()));
params.addQueryItem("mode", QString::number(c.mode));
task.data = QUrl::toPercentEncoding(params.query(QUrl::FullyEncoded), "%=&", "-.~_");
task.state = Code;
forward();
break;
}
case Code:{
int code = QString(reply->readAll()).toInt();
emit stateChanged(task.state = code > 0 ? None : code);
dequeue();
break;
}
}
};
auto avRegular = [](QString code){
static QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?");
r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
return r.match(code).capturedLength() == code.length();
};
d->pool.append({ avRegular, 0, avProcess });
connect(this, &Post::stateChanged, [this](int code){
switch (code){
case None:
case Code:
break;
default:
{
Q_D(Post);
if (!d->tryNext()){
emit errorOccured(code);
}
break;
}
}
});
}
示例4: report_error
// TODO: This looks like should be ported to C code. or a big part of it.
bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, const bool selected)
{
static const char errPrefix[] = "divelog.de-upload:";
if (!amount_selected) {
report_error(tr("no dives were selected").toUtf8());
return false;
}
xsltStylesheetPtr xslt = NULL;
struct zip *zip;
xslt = get_stylesheet("divelogs-export.xslt");
if (!xslt) {
qDebug() << errPrefix << "missing stylesheet";
return false;
}
int error_code;
zip = zip_open(QFile::encodeName(QDir::toNativeSeparators(tempfile)), ZIP_CREATE, &error_code);
if (!zip) {
char buffer[1024];
zip_error_to_str(buffer, sizeof buffer, error_code, errno);
report_error(tr("failed to create zip file for upload: %s").toUtf8(), buffer);
return false;
}
/* walk the dive list in chronological order */
int i;
struct dive *dive;
for_each_dive (i, dive) {
FILE *f;
char filename[PATH_MAX];
int streamsize;
char *membuf;
xmlDoc *transformed;
struct zip_source *s;
/*
* Get the i'th dive in XML format so we can process it.
* We need to save to a file before we can reload it back into memory...
*/
if (selected && !dive->selected)
continue;
QString innerTmpFile = tempfile;
QString tmpSuffix = QString::number(qrand() % 9999) + ".tmp";
innerTmpFile.replace(".dld", tmpSuffix);
f = subsurface_fopen(QFile::encodeName(QDir::toNativeSeparators(innerTmpFile)), "w+");
if (!f) {
report_error(tr("cannot create temporary file: %s").toUtf8(), qt_error_string().toUtf8().data());
goto error_close_zip;
}
save_dive(f, dive);
fseek(f, 0, SEEK_END);
streamsize = ftell(f);
rewind(f);
membuf = (char *)malloc(streamsize + 1);
if (!membuf || (streamsize = fread(membuf, 1, streamsize, f)) == 0) {
report_error(tr("internal error: %s").toUtf8(), qt_error_string().toUtf8().data());
fclose(f);
free((void *)membuf);
goto error_close_zip;
}
membuf[streamsize] = 0;
fclose(f);
unlink(QFile::encodeName(QDir::toNativeSeparators(innerTmpFile)));
/*
* Parse the memory buffer into XML document and
* transform it to divelogs.de format, finally dumping
* the XML into a character buffer.
*/
xmlDoc *doc = xmlReadMemory(membuf, streamsize, "divelog", NULL, 0);
if (!doc) {
qWarning() << errPrefix << "could not parse back into memory the XML file we've just created!";
report_error(tr("internal error").toUtf8());
free((void *)membuf);
goto error_close_zip;
}
free((void *)membuf);
transformed = xsltApplyStylesheet(xslt, doc, NULL);
xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize);
xmlFreeDoc(doc);
xmlFreeDoc(transformed);
/*
* Save the XML document into a zip file.
*/
snprintf(filename, PATH_MAX, "%d.xml", i + 1);
s = zip_source_buffer(zip, membuf, streamsize, 1);
if (s) {
int64_t ret = zip_add(zip, filename, s);
if (ret == -1)
qDebug() << errPrefix << "failed to include dive:" << i;
}
}
示例5: qrand
/**
* @brief GameMaster::losujWroga Metoda losująca przeciwnika z zadanej grupy.
* @param grupa indeks grupy, z której ma być losowany przeciwnik.
* @return Wskaźnik na wylosowanego przeciwnika.
*/
Enemy * GameMaster::generateEnemy(int enemyGroup)
{
int idx = qrand() % enemyGroups_[enemyGroup]->size();
return enemies_[enemyGroups_[enemyGroup]->at(idx)];
}
示例6: qrand
bool DkUtils::compRandom(const QFileInfo&, const QFileInfo&) {
return qrand() % 2 != 0;
}
示例7: switch
QVariant PayloadProtocol::fieldData(int index, FieldAttrib attrib,
int streamIndex) const
{
switch (index)
{
case payload_dataPattern:
switch(attrib)
{
case FieldName:
return QString("Data");
case FieldValue:
return data.pattern();
case FieldTextValue:
return QString(fieldData(index, FieldFrameValue,
streamIndex).toByteArray().toHex());
case FieldFrameValue:
{
QByteArray fv;
int dataLen;
dataLen = protocolFrameSize(streamIndex);
// FIXME: Hack! Bad! Bad! Very Bad!!!
if (dataLen <= 0)
dataLen = 1;
fv.resize(dataLen+4);
switch(data.pattern_mode())
{
case OstProto::Payload::e_dp_fixed_word:
for (int i = 0; i < (dataLen/4)+1; i++)
qToBigEndian((quint32) data.pattern(),
(uchar*)(fv.data()+(i*4)) );
break;
case OstProto::Payload::e_dp_inc_byte:
for (int i = 0; i < dataLen; i++)
fv[i] = i % (0xFF + 1);
break;
case OstProto::Payload::e_dp_dec_byte:
for (int i = 0; i < dataLen; i++)
fv[i] = 0xFF - (i % (0xFF + 1));
break;
case OstProto::Payload::e_dp_random:
//! \todo (HIGH) cksum is incorrect for random pattern
for (int i = 0; i < dataLen; i++)
fv[i] = qrand() % (0xFF + 1);
break;
default:
qWarning("Unhandled data pattern %d",
data.pattern_mode());
}
fv.resize(dataLen);
return fv;
}
default:
break;
}
break;
// Meta fields
case payload_dataPatternMode:
switch(attrib)
{
case FieldValue: return data.pattern_mode();
default: break;
}
break;
default:
break;
}
return AbstractProtocol::fieldData(index, attrib, streamIndex);
}
示例8: askForChoice
QString TrustAI::askForChoice(const QString &, const QString &choice, const QVariant &) {
QStringList choices = choice.split("+");
return choices.at(qrand() % choices.length());
}
示例9: Q_UNUSED
ServerPlayer *TrustAI::askForPlayerChosen(const QList<ServerPlayer *> &targets, const QString &reason) {
Q_UNUSED(reason);
int r = qrand() % targets.length();
return targets.at(r);
}
示例10: QColor
/**
* @brief Icon::Icon
* Ikona o losowym kolorze i rozmiarze 10x10
*/
Icon::Icon()
{
this->color = QColor((float)qrand()/RAND_MAX*255, (float)qrand()/RAND_MAX*255, (float)qrand()/RAND_MAX*255);
this->geometry = Geometry(0, 0, 10, 10);
}
示例11: askForSuit
Card::Suit TrustAI::askForSuit(const QString &) {
return Card::AllSuits[qrand() % 4];
}
示例12: QString
bool DesktopWindow::pickWallpaper() {
if(slideShowInterval_ <= 0
|| !QFileInfo(wallpaperDir_).isDir()) {
return false;
}
QList<QByteArray> formats = QImageReader::supportedImageFormats();
QStringList formatsFilters;
for (const QByteArray& format: formats)
formatsFilters << QString("*.") + format;
QDir folder(wallpaperDir_);
QStringList files = folder.entryList(formatsFilters,
QDir::Files | QDir::NoDotAndDotDot,
QDir::Name);
if(!files.isEmpty()) {
QString dir = wallpaperDir_ + QLatin1Char('/');
if(!wallpaperRandomize_) {
if(!lastSlide_.startsWith(dir)) { // not in the directory
wallpaperFile_ = dir + files.first();
}
else {
QString ls = lastSlide_.remove(0, dir.size());
if(ls.isEmpty() // invalid
|| ls.contains(QLatin1Char('/'))) { // in a subdirectory or invalid
wallpaperFile_ = dir + files.first();
}
else {
int index = files.indexOf(ls);
if(index == -1) { // removed or invalid
wallpaperFile_ = dir + files.first();
}
else {
wallpaperFile_ = dir + (index + 1 < files.size()
? files.at(index + 1)
: files.first());
}
}
}
}
else {
if(files.size() > 1) {
if(lastSlide_.startsWith(dir)) {
QString ls = lastSlide_.remove(0, dir.size());
if(!ls.isEmpty() && !ls.contains(QLatin1Char('/')))
files.removeOne(ls); // choose from other images
}
// this is needed for the randomness, especially when choosing the first wallpaper
qsrand((uint)QTime::currentTime().msec());
int randomValue = qrand() % files.size();
wallpaperFile_ = dir + files.at(randomValue);
}
else {
wallpaperFile_ = dir + files.first();
}
}
if (lastSlide_ != wallpaperFile_) {
lastSlide_ = wallpaperFile_;
Settings& settings = static_cast<Application*>(qApp)->settings();
settings.setLastSlide(lastSlide_);
return true;
}
}
return false;
}
示例13: Q_ASSERT_X
void CountryByShape::postQuestion( QObject *gameObject )
{
//Find a random placemark
Q_ASSERT_X( d->m_countryNames, "CountryByShape::postQuestion",
"CountryByShapePrivate::m_countryNames is NULL" );
QVector<GeoDataPlacemark*> countryPlacemarks = d->m_countryNames->placemarkList();
uint randomSeed = uint(QTime::currentTime().msec());
qsrand( randomSeed );
bool found = false;
GeoDataPlacemark *placemark =0;
GeoDataPoint *point = 0;
GeoDataCoordinates coord;
GeoDataLatLonAltBox box;
QVariantList answerOptions;
while ( !found ) {
int randomIndex = qrand()%countryPlacemarks.size();
placemark = countryPlacemarks[randomIndex];
point = dynamic_cast<GeoDataPoint*>( placemark->geometry() );
coord = point->coordinates();
if ( point ) {
/**
* Find the country geometry and fetch corresponding
* GeoDataLatLonAltBox to zoom in to that country so that
* it fills the viewport.
*/
Q_ASSERT_X( d->m_countryBoundaries, "CountryByShape::postQuestion",
"CountryByShapePrivate::m_countryBoundaries is NULL" );
QVector<GeoDataFeature*>::Iterator i = d->m_countryBoundaries->begin();
QVector<GeoDataFeature*>::Iterator const end = d->m_countryBoundaries->end();
for ( ; i != end; ++i ) {
GeoDataPlacemark *country = static_cast<GeoDataPlacemark*>( *i );
GeoDataPolygon *polygon = dynamic_cast<GeoDataPolygon*>( country->geometry() );
GeoDataLinearRing *linearring = dynamic_cast<GeoDataLinearRing*>( country->geometry() );
GeoDataMultiGeometry *multigeom = dynamic_cast<GeoDataMultiGeometry*>( country->geometry() );
if ( polygon &&
polygon->contains( coord ) &&
!d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) )
{
box = polygon->latLonAltBox();
found = true;
break;
}
if ( linearring &&
linearring->contains( coord ) &&
!d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) )
{
box = linearring->latLonAltBox();
found = true;
break;
}
if ( multigeom ) {
QVector<GeoDataGeometry*>::Iterator iter = multigeom->begin();
QVector<GeoDataGeometry*>::Iterator const end = multigeom->end();
for ( ; iter != end; ++iter ) {
GeoDataPolygon *poly = dynamic_cast<GeoDataPolygon*>( *iter );
if ( poly &&
poly->contains( coord ) &&
!d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) )
{
box = poly->latLonAltBox();
found = true;
break;
}
}
}
if ( found ) {
break;
}
}
}
}
d->m_marbleWidget->setHighlightEnabled( true );
emit announceHighlight( coord.longitude(GeoDataCoordinates::Degree),
coord.latitude(GeoDataCoordinates::Degree),
GeoDataCoordinates::Degree );
/**
* Now disable the highlight feature so that
* the user click doesn't disturbe the highlight
* we did to ask question.
*/
d->m_marbleWidget->setHighlightEnabled( false );
d->m_marbleWidget->centerOn( box, true );
answerOptions << placemark->name()
<< countryPlacemarks[qrand()%countryPlacemarks.size()]->name()
<< countryPlacemarks[qrand()%countryPlacemarks.size()]->name()
<< countryPlacemarks[qrand()%countryPlacemarks.size()]->name();
//.........这里部分代码省略.........
示例14: if
{
i++;
}
else
{
i = m_randomArenaModeArenaList.erase(i);
}
}
if(m_randomArenaModeArenaList.isEmpty())
{
m_randomArenaModeArenaList = arenasAvailable;
}
}
int nIndex = (static_cast<double>(qrand()) / RAND_MAX) * m_randomArenaModeArenaList.count();
if(nIndex < 0)
{
nIndex = 0;
}
else if(nIndex >= m_randomArenaModeArenaList.count())
{
nIndex = m_randomArenaModeArenaList.count() - 1;
}
filePath = m_randomArenaModeArenaList.at(nIndex);
m_randomArenaModeArenaList.removeAt(nIndex);
}
else
{
filePath = QStandardPaths::locate(QStandardPaths::AppDataLocation, Settings::self()->arena());
}
示例15: return
int Apipa::rand(int min, int max)
{
return ((((int)((double)qrand() / (double)RAND_MAX)) * (max - min + 1)) + min);
}