如果您不想修改原始数据并且只访问每个元素一次,您可以对索引向量进行打乱:
#include <algorithm>
#include <random>
auto engine = std::default_random_engine{};
const std::vector<int> numbers = {4, 5, 7, 12};
std::vector<int> indices(numbers.size());
std::iota(indices.begin(), indices.end(), 0);
std::shuffle(indices.begin(), indices.end(), engine);
for (auto i : indices)
{
std::cout << numbers[i] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4096 次 |
| 最近记录: |