I am porting a Java program to C++. I have a piece of code to shuffle two arrays simultaneously in Java, which produces a way to return the indices of the shuffled array so could to used to relocate another array (of the same length) accordingly. In C++, I shuffle the vectors with the following algorithm
#include <vector>
#include <algorithm>
#include <random>
#include <iostream>
using namespace std;
int main(void) {
vector<int> A, B;
for (int n=0; n<10; n++) {
A.push_back(n);
B.push_back(n);
}
std::random_device rd;
std::mt19937 gen;
std::uniform_int_distribution<> rnd(0, A.size()-1);
for (int n=0; n<A.size(); n++) {
int m = rnd(gen);
std::swap(A[n], A[m]);
std::swap(B[n], B[m]);
}
for (auto it: A) cout << it << " ";
cout << endl;
for (auto it: B) cout << it << " ";
cout << endl;
return 0;
}
It works. But I wonder if there is any STL algorithm that can simultaneously shuffle two or more containers.
Aucun commentaire:
Enregistrer un commentaire