对c++中的vector进行随机排序,打乱原有顺序:
#include <vector>
#include <io.h>
#include <random>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v)
{
os << "{ ";
for (const auto &i : v) {
os << i << ", ";
}
os << "}";
return os;
}
auto get_URBG()
{
std::random_device rd;
std::mt19937 g(rd());
return g;
}
// 随机排序容器内元素,打印随机排序前和随机排序后的容器内容
template <typename T>
void shuffle_container(std::vector<T> &container)
{
//std::cout << "before shuffle: " << container << std::endl;
std::shuffle(container.begin(), container.end(), get_URBG());
//std::cout << "after shuffle: " << container << std::endl;
}
void main()
{
std::vector<int> testVec{1,2,4,6,9};
shuffle_container(testVec);
}