在隨機生成一定范圍不重復數時用到random_shuffle函數,之前填充數組都是用for循環,
想到之前python中的range生成序列,於是在C++中找到對應的generate用來生成所需數組。
用來生成元素,並填充到一個序列中
generate:
1 template <class ForwardIterator, class Generator> 2 void generate ( ForwardIterator first, ForwardIterator last, Generator gen ) 3 { 4 while (first != last) { 5 *first = gen(); 6 ++first; 7 } 8 }
Generator gen生成器,是一個不接受參數,且有返回參數的函數,first和last是生成的范圍。
generate_n:
void generate_n (OutputIterator first, Size n, Generator gen);
first插入起始位置,n插入元素個數,gen元素生成器.
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 #include<time.h> 5 #include <iterator> 6 using namespace std; 7 8 int nextNum() { 9 static int n = 1; 10 return n++; 11 12 } 13 14 class Range_generate{ 15 private: 16 int m_Value; 17 int m_interval; 18 public: 19 Range_generate(int value,int interval) {m_Value=value-interval;m_interval=interval;} 20 int operator()(){ 21 return m_Value+=m_interval;} 22 }; //Lambda是函數對象(Function Object)的語法糖,Lambda最終會被轉換成所示的Functor類 23 24 int main(){ 25 srand((unsigned int) time(NULL)); 26 vector<int> array(10); 27 generate(array.begin(),array.end(),[]{return rand()%10;}); 28 for(vector<int>::iterator ptr=array.begin();ptr!=array.end();){ 29 cout<<*ptr++<<" "; 30 //ptr++; 31 } 32 cout<<endl; 33 generate(array.begin(),array.end(),Range_generate(1,2)); //首項1,間隔2 34 ostream_iterator<int> screen(cout," "); 35 copy(array.begin(),array.end(),screen); 36 system("pause"); 37 return 0; 38 }