將[First, Last)區間中的元素次序打亂重新洗牌,使用你給定的隨機數引擎_Func
使用一個均勻分佈隨機數產生器打亂[First, Last)區間內的元素次序
使用_RngFunc打亂[First, Last)區間內的元素次序.算法內部使用一個整數值來調用_RngFunc(max),返回一個大於0,小於max的隨機數,不包括max本身
複雜度:線性,執行numElems-1次交換
使用例子:
template<typename T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
for (int i = first; i <= last; ++i)
{
coll.insert(coll.end(), i);
}
}
template<typename T>
inline void PRINT_ELEMENTS(const T & coll, const string& optcstr = "")
{
cout << optcstr;
for (auto elem : coll)
{
cout << elem << ' ';
}
cout << endl;
}
int main()
{
vector<int>a;
INSERT_ELEMENTS(a, 1, 9);
PRINT_ELEMENTS(a, "a: ");
random_shuffle(a.begin(), a.end());
PRINT_ELEMENTS(a, "shuffled: ");
sort(a.begin(), a.end());
PRINT_ELEMENTS(a, "sorted: ");
default_random_engine dre;
shuffle(a.begin(), a.end(), dre);
PRINT_ELEMENTS(a, "shuffled: ");
}
使用自定義的隨機數生成器傳給random_shuffle:
template<typename T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
for (int i = first; i <= last; ++i)
{
coll.insert(coll.end(), i);
}
}
template<typename T>
inline void PRINT_ELEMENTS(const T & coll, const string& optcstr = "")
{
cout << optcstr;
for (auto elem : coll)
{
cout << elem << ' ';
}
cout << endl;
}
class MyRandom
{
public:
ptrdiff_t operator()(ptrdiff_t max)
{
double tmp;
tmp = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
return static_cast<ptrdiff_t>(tmp * max);
}
};
int main()
{
vector<int>a;
INSERT_ELEMENTS(a, 1, 9);
PRINT_ELEMENTS(a, "a: ");
MyRandom rd;
random_shuffle(a.begin(), a.end(), rd);
PRINT_ELEMENTS(a, "shuffled: ");
}