jeudi 1 septembre 2022

remove an element from the back of a vector after shuffling it c++

so the purpose of the code is to shuffle a vector, then print a random number from the vector, and then delete that same number so it won't repeat. what I did is:

  1. there is an initialized vector called songs, first I used random_device to make a random func.
  2. I initialized an iterator to the back of the vector.
  3. I shuffled the vector
  4. Print
  5. remove the last element that I printed (after shuffling).

The problem is when I do songs.pop_back(); it removes the last element from the original vector and not from the shuffled one, so it makes numbers coming back that way. and I get an error.

code:

int getSong(int n, vector<int> songs, vector<int>::iterator iter) {
    random_device random;
    shuffle(songs.begin(), songs.end(), random);
    for (int j = 0; j < n; j++) {
        cout << songs[j] << " ";
    }
    iter = songs.end() -1 ;
    int song = *iter;
    iter--;
    return song;
}

int main() {

    vector<int> songs = { 1,2,3,4,5,6,7,8,9 };
    int n = songs.size();
    vector<int>::iterator iter;
    for (int i = 0; i < n; n--) {
        int l = getSong(n, songs, iter);
        cout << "The song number is:" << l << "\n" << endl;
        songs.pop_back();
    }

    return 0;
}

the output is: enter image description here

Thank you!




Aucun commentaire:

Enregistrer un commentaire