std::shuffle-c++
生活随笔
收集整理的這篇文章主要介紹了
std::shuffle-c++
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在Python中我們會經(jīng)常看到shuffle的隨機排列函數(shù),其可以將列表中的內(nèi)容進(jìn)行隨機排列,但在C++中卻需要自己去實現(xiàn)這樣功能的函數(shù)(c++0x之前)。在c++0x之后這樣的功能函數(shù)在標(biāo)準(zhǔn)庫中已有對應(yīng)的提供——std::shuffle。下面就對該函數(shù)做具體的介紹: [cpp]?view plaincopy template?<class?RandomAccessIterator,?class?URNG>?? void?shuffle?(RandomAccessIterator?first,?RandomAccessIterator?last,?URNG&&?g);??
函數(shù)功能:使用隨機生成器g對元素[first, last)可行交換的容器內(nèi)部元素進(jìn)行隨機排列,大概原理類似如下代碼的功能 [cpp]?view plaincopytemplate?<class?RandomAccessIterator,?class?URNG>?? void?shuffle?(RandomAccessIterator?first,?RandomAccessIterator?last,?URNG&&?g)?? {?? ??for?(auto?i?=?(last-first)?-?1;?i?>?0;?--i)?{?? ????std::uniform_int_distribution<decltype(i)>?d?(0,i);?? ????swap?(first[i],?first[d?(g)]);?? ??}?? }?? 函數(shù)必須與標(biāo)準(zhǔn)庫默認(rèn)的隨機生成器一起使用,隨機生成器的頭文件是<random>。如果要使用不需要傳入隨機生成器函數(shù)可以參照random_shuffle函數(shù)。 參數(shù): first, last 順序容器迭代器的開頭(begin)和結(jié)尾(end),在[first, end)這個區(qū)間內(nèi)的數(shù)值將會被隨機排序。順序容器的迭代器必須是定義有swap函數(shù)的數(shù)據(jù)類型以及順序容器也必須支持元素可交換。 g 唯一隨機數(shù)生成器的一個實例,在頭文件<random>中定義。URNG?是?uniform random number generator的縮寫。 返回值: None 用例: [cpp]?view plaincopy #include?<iostream>?? #include?<vector>?? #include?<algorithm>?//?std::move_backward?? #include?<random>?//?std::default_random_engine?? #include?<chrono>?//?std::chrono::system_clock?? ?? int?main?(int?argc,?char*?argv[])?? {?? ????std::vector<int>?v;?? ?? ????for?(int?i?=?0;?i?<?10;?++i)?{?? ????????v.push_back?(i);?? ????}?? ?? ????//?obtain?a?time-based?seed:?? ????unsigned?seed?=?std::chrono::system_clock::now?().time_since_epoch?().count?();?? ????std::shuffle?(v.begin?(),?v.end?(),?std::default_random_engine?(seed));?? ?? ????for?(auto&?it?:?v)?{?? ????????std::cout?<<?it?<<?"?";?? ????}?? ?? ????std::cout?<<?"\n";?? ?? ????return?0;?? }??
編譯: g++ main.cpp -o shuffle -std=c++0x 執(zhí)行輸出: 6 4 2 3 7 8 5 1 9 0 4 7 3 6 8 0 2 9 5 1
函數(shù)功能:使用隨機生成器g對元素[first, last)可行交換的容器內(nèi)部元素進(jìn)行隨機排列,大概原理類似如下代碼的功能 [cpp]?view plaincopy
編譯: g++ main.cpp -o shuffle -std=c++0x 執(zhí)行輸出: 6 4 2 3 7 8 5 1 9 0 4 7 3 6 8 0 2 9 5 1
轉(zhuǎn)載于:https://www.cnblogs.com/lx-hhxxttxs/p/5908213.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的std::shuffle-c++的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Xcode中的Info.plist字段列
- 下一篇: iOS单例详解