简体   繁体   English

洗牌后从向量后面删除一个元素 c++

[英]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.有一个名为歌曲的初始化向量,首先我使用 random_device 来制作随机函数。
  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();问题是当我做 song.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: output 是: 在此处输入图像描述

Thank you!谢谢!

I would write something like this instead:我会写这样的东西:

int getSong( vector<int>& songs ) {
    random_device random;
    shuffle(songs.begin(), songs.end(), random);
    for ( int song : songs ) {
        cout << song << " ";
    }
    cout << endl;
    return *songs.rbegin();
}

int main() {
    vector<int> songs = { 1,2,3,4,5,6,7,8,9 };
    while( !songs.empty() )  {
        int l = getSong(songs);
        cout << "The song number is:" << l << "\n" << endl;
        songs.pop_back();
    }
    return 0;
}

https://godbolt.org/z/oWbxvMjE3 https://godbolt.org/z/oWbxvMjE3

Produces:产生:

Program stdout

5 3 6 8 1 9 7 4 2 
The song number is:2

7 3 5 8 6 9 1 4 
The song number is:4

6 1 9 8 3 5 7 
The song number is:7

3 6 1 5 8 9 
The song number is:9

6 8 5 3 1 
The song number is:1

8 5 3 6 
The song number is:6

3 5 8 
The song number is:8

3 5 
The song number is:5

3 
The song number is:3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM