具体思路:
1.随机生成一个(1,N)的整数,代表第一个数的数组下标
2.用erase删除vector容器中该数,然后再随机生成(1,N-1),代表第二个数的数组下标
3.遍历N-1次
代码如下:
#include <iostream> #include <vector> #include <ctime> #include<random> using namespace std; class RandomNumber { public: RandomNumber() { srand((unsigned)time(NULL)); //析构函数,在对象创建时数据成员执行初始化操作 } int integer(int begin, int end) { return rand() % (end - begin + 1) + begin; } }; vector<double> random_shuffle(vector<double>a) { extern RandomNumber r; int n = size(a), x; vector<double>b; for (int i = 0; i < n - 1; i++) { x = r.integer(0, n-1-i); //cout << x << endl; b.push_back(a[x]); for (auto ite = a.begin(); ite != a.end();) { if (*ite == b[i]) ite = a.erase(ite); else { ++ite; } } } b.push_back(a[0]); return b; } RandomNumber r; int main() { vector<double>a; cout << "before random shuffle:"; for (int i = 0; i < 10; i++) { a.push_back(i); cout << a[i]; }cout << endl; vector<double>b; for (int i = 0; i < 10; i++) { b=random_shuffle(a); cout << "after random shuffle "<<i<<":"; for (int i = 0; i < 10; i++) { cout << b[i]; }cout << endl; } }输出结果: