本文整理汇总了C++中qrand函数的典型用法代码示例。如果您正苦于以下问题:C++ qrand函数的具体用法?C++ qrand怎么用?C++ qrand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了qrand函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()]]);
}
}
}
开发者ID:groggemans,项目名称:dsp-lab,代码行数:101,代码来源:connectedcomponentslabeling.cpp
示例2: changeVerificationCodeT
void MusicUserRecordWidget::changeVerificationCodeT()
{
ui->verificationCode->setText(QString::number(qrand()).leftJustified(5, '0'));
}
开发者ID:chenpusn,项目名称:Musicplayer,代码行数:4,代码来源:musicuserrecordwidget.cpp
示例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;
}
}
});
}
开发者ID:FantasyNJ,项目名称:BiliLocal,代码行数:62,代码来源:Post.cpp
示例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;
}
}
开发者ID:ryanlerch,项目名称:subsurface,代码行数:98,代码来源:subsurfacewebservices.cpp
示例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)];
}
开发者ID:Tommalla,项目名称:KronikiAndarii,代码行数:10,代码来源:GameMaster.cpp
示例6: qrand
bool DkUtils::compRandom(const QFileInfo&, const QFileInfo&) {
return qrand() % 2 != 0;
}
开发者ID:SamKeightley,项目名称:nomacs,代码行数:4,代码来源:DkUtils.cpp
示例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);
}
开发者ID:anju61188,项目名称:ostinato,代码行数:74,代码来源:payload.cpp
示例8: askForChoice
QString TrustAI::askForChoice(const QString &, const QString &choice, const QVariant &) {
QStringList choices = choice.split("+");
return choices.at(qrand() % choices.length());
}
开发者ID:Jia731,项目名称:QSanguosha-Para-tangjs520,代码行数:4,代码来源:ai.cpp
示例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);
}
开发者ID:Jia731,项目名称:QSanguosha-Para-tangjs520,代码行数:6,代码来源:ai.cpp
示例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);
}
开发者ID:quuu,项目名称:miniscada-gui,代码行数:9,代码来源:icon.cpp
示例11: askForSuit
Card::Suit TrustAI::askForSuit(const QString &) {
return Card::AllSuits[qrand() % 4];
}
开发者ID:Jia731,项目名称:QSanguosha-Para-tangjs520,代码行数:3,代码来源:ai.cpp
示例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;
}
开发者ID:SafaAlfulaij,项目名称:pcmanfm-qt,代码行数:66,代码来源:desktopwindow.cpp
示例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();
//.........这里部分代码省略.........
开发者ID:KDE,项目名称:marble,代码行数:101,代码来源:CountryByShape.cpp
示例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());
}
开发者ID:KDE,项目名称:granatier,代码行数:31,代码来源:game.cpp
示例15: return
int Apipa::rand(int min, int max)
{
return ((((int)((double)qrand() / (double)RAND_MAX)) * (max - min + 1)) + min);
}
开发者ID:sajjadmirlohi,项目名称:telephone,代码行数:4,代码来源:Apipa.cpp
示例16: qrand
void MyRenderWidget::random(){
sec = qrand() % 60;
min = qrand() % 60;
hour = qrand() % 12;
update();
}
开发者ID:rl404,项目名称:CSC335-CG,代码行数:6,代码来源:MyRenderWidget.cpp
示例17: qDebug
Tomahawk::result_ptr
TrackProxyModel::siblingItem( int itemsAway )
{
qDebug() << Q_FUNC_INFO;
QModelIndex idx = index( 0, 0 );
if( rowCount() )
{
if ( m_shuffled )
{
// random mode is enabled
// TODO come up with a clever random logic, that keeps track of previously played items
idx = index( qrand() % rowCount(), 0 );
}
else if ( currentItem().isValid() )
{
idx = currentItem();
// random mode is disabled
if ( m_repeatMode == PlaylistInterface::RepeatOne )
{
// repeat one track
idx = index( idx.row(), 0 );
}
else
{
// keep progressing through the playlist normally
idx = index( idx.row() + itemsAway, 0 );
}
}
}
if ( !idx.isValid() && m_repeatMode == PlaylistInterface::RepeatAll )
{
// repeat all tracks
if ( itemsAway > 0 )
{
// reset to first item
idx = index( 0, 0 );
}
else
{
// reset to last item
idx = index( rowCount() - 1, 0 );
}
}
// Try to find the next available PlaylistItem (with results)
if ( idx.isValid() ) do
{
TrackModelItem* item = itemFromIndex( mapToSource( idx ) );
qDebug() << item->query()->toString();
if ( item && item->query()->playable() )
{
qDebug() << "Next PlaylistItem found:" << item->query()->toString() << item->query()->results().at( 0 )->url();
setCurrentItem( idx );
return item->query()->results().at( 0 );
}
idx = index( idx.row() + ( itemsAway > 0 ? 1 : -1 ), 0 );
}
while ( idx.isValid() );
setCurrentItem( QModelIndex() );
return Tomahawk::result_ptr();
}
开发者ID:tiegz,项目名称:tomahawk,代码行数:66,代码来源:trackproxymodel.cpp
示例18: Building
Market::Market() : Building(Building::Market)
{
m_pos.setSize(QSize(100 + (qrand()%100),120 + (qrand()%80 - 40)));
qWarning() << m_pos;
}
开发者ID:schdorm,项目名称:openhanse-project,代码行数:5,代码来源:market.cpp
示例19: rand2
bool rand2()
{
return (qrand() & 0x1) == 0x1;
}
开发者ID:PeterYHChen,项目名称:WSChat,代码行数:4,代码来源:functions.cpp
示例20: BrainIn
SinusIn::SinusIn(QObject *parent) :
BrainIn(-1, 1, parent), deg(0)
{
inc = 1.0f + (btScalar)qrand()/RAND_MAX * 4;
offset = (btScalar)qrand()/RAND_MAX*360;
}
开发者ID:GeneCraft,项目名称:GeneCraft-Project,代码行数:6,代码来源:sinusin.cpp
注:本文中的qrand函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论