對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);
}