Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to sort a QStringList by random



  • I am writing a program of poker game, and I store a pack of 52 cards in QStringList.
    How to shuffle the QStringList by random ?

    QStringList poker;
    for(int i=1;i<14;i++){
        QString s = "diamond" + QString::number(i);
        poker << s;
    }
    for(int i=1;i<14;i++){
        QString s = "spade" + QString::number(i);
        poker << s;
    }
    for(int i=1;i<14;i++){
        QString s = "heart" + QString::number(i);
        poker << s;
    }
    for(int i=1;i<14;i++){
        QString s = "club" + QString::number(i);
        poker << s;
    }
    for(int i=1;i<3;i++){
        QString s = "joker" + QString::number(i);
        poker << s;
    }
    qDebug() << poker;
    // ("diamond1", "diamond2", "diamond3", "diamond4", "diamond5", "diamond6", "diamond7", "diamond8", "diamond9", "diamond10", "diamond11", "diamond12", "diamond13", "spade1", "spade2", "spade3", "spade4", "spade5", "spade6", "spade7", "spade8", "spade9", "spade10", "spade11", "spade12", "spade13", "heart1", "heart2", "heart3", "heart4", "heart5", "heart6", "heart7", "heart8", "heart9", "heart10", "heart11", "heart12", "heart13", "club1", "club2", "club3", "club4", "club5", "club6", "club7", "club8", "club9", "club10", "club11", "club12", "club13", "joker1", "joker2")
    

  • Lifetime Qt Champion

    Hi,

    std::shuffle might be what you want.



  • @SGaist OK!

    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(poker.begin(), poker.end(), g);
    

Log in to reply