Certainly! Here's a C++ function that takes a std::vector<std::vector<float>> as input, shuffles each inner vector independently, and returns a new vector of vectors without modifying the original:
#include <vector>
#include <algorithm> // for std::shuffle
#include <random> // for std::random_device, std::mt19937
std::vector<std::vector<float>> shuffleInnerVectors(const std::vector<std::vector<float>>& input) {
// Create a copy of the input to shuffle
std::vector<std::vector<float>> result = input;
// Random number generator setup
std::random_device rd;
std::mt19937 gen(rd());
// Shuffle each inner vector
for (auto& innerVec : result) {
std::shuffle(innerVec.begin(), innerVec.end(), gen);
}
return result;
}
Explanation:
- The function takes the input vector by const reference to avoid copying initially.
- It copies the input to
result so the original remains unchanged.
- It uses a random number generator (
std::mt19937) seeded with std::random_device.
- Each inner vector is shuffled independently using
std::shuffle.
- Finally, the shuffled copy is returned.
Example usage:
#include <iostream>
int main() {
std::vector<std::vector<float>> data = {
{1.0f, 2.0f, 3.0f},
{4.0f, 5.0f, 6.0f, 7.0f},
{8.0f, 9.0f}
};
auto shuffled = shuffleInnerVectors(data);
// Print original
std::cout << "Original:\n";
for (const auto& vec : data) {
for (float f : vec) std::cout << f << ' ';
std::cout << '\n';
}
// Print shuffled
std::cout << "\nShuffled:\n";
for (const auto& vec : shuffled) {
for (float f : vec) std::cout << f << ' ';
std::cout << '\n';
}
return 0;
}
This will show the original vectors unchanged and the new vectors shuffled independently.