[英]remove an element from the back of a vector after shuffling it c++
所以代码的目的是打乱一个向量,然后从向量中打印一个随机数,然后删除相同的数字,这样它就不会重复了。 我所做的是:
问题是当我做 song.pop_back(); 它从原始向量中删除最后一个元素,而不是从洗牌的向量中删除,因此它使数字以这种方式返回。 我得到一个错误。
代码:
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;
}
谢谢!
我会写这样的东西:
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
产生:
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.