⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shuffle.cpp

📁 C++&datastructure书籍源码,以前外教提供现在与大家共享
💻 CPP
字号:
#include <iostream>
#include <string>
using namespace std;

#include "tvector.h"
#include "randgen.h"

struct Track
{
    string title;   // title of song/track
    int    number;  // the original track number
    
    Track::Track()
      : title("no title"),
        number(0)
    { }
    
    Track::Track(const string& t, int n)
      : title(t),
        number(n)
    { }
};

void Print(const tvector<Track>& tracks, int count)
// precondition: there are count locations in tracks
// postcondition: contents of tracks printed
{
    int k;
    for(k=0; k < count; k++)
    {    cout << tracks[k].number << "\t" << tracks[k].title << endl;
    }
}

void Shuffle(tvector<Track> & tracks,int count)
// precondition: count = # of entries in tracks
// postcondition: entries in tracks have been randomly shuffled     
{
    RandGen gen;    // for random # generator
    int randTrack;
    Track temp;
    int k;    
    // choose a random song from [k..count-1] for song # k
    
    for(k=0; k < count - 1; k++)
    {   randTrack = gen.RandInt(k,count-1);   // random track
        temp = tracks[randTrack];             // swap entries
        tracks[randTrack] = tracks[k];
        tracks[k] = temp;
    }
}

int main()
{
    tvector<Track> tracks(10);
    
    tracks[0] = Track("Box of Rain",1);
    tracks[1] = Track("Friend of the Devil",2);
    tracks[2] = Track("Sugar Magnolia",3);
    tracks[3] = Track("Operator",4);
    tracks[4] = Track("Candyman",5);
    tracks[5] = Track("Ripple",6);
    tracks[6] = Track("Brokedown Palace",7);
    tracks[7] = Track("Till the Morning Comes",8);
    tracks[8] = Track("Attics of my Life",9);
    tracks[9] = Track("Truckin",10);
    
    Print(tracks,10);
    Shuffle(tracks,10);
    cout << endl << "---- after shuffling ----" << endl << endl;
    Print(tracks,10);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -