C ++ uses STL to generate random sequences of ordered sequences

Source: Internet
Author: User
Tags random seed

see the following example.

Ptrdiff_t myrandom (ptrdiff_t I) {return rand () % I ;}< br/> ptrdiff_t (* p_myrandom) (ptrdiff_t) = myrandom; // a function pointer is defined here, method function pointing to random number generation <br/> template <typename T> void vrand (vector <t> & V, ptrdiff_t (* p_myrandom) (ptrdiff_t )) <br/> // define a template function, which can change an ordered sequence to a random sequence <br/> {<br/> If (p_myrandom = NULL) <br/>{< br/> random_shuffle (v. begin (), V. end (); // call the template function in STL to generate a random sequence <br/>}< br/> else <br/>{< br/> random_shuffle (v. B Egin (), V. end (), p_myrandom); // you can call the template function in STL to generate a random sequence with one more parameter, method to generate a random number <br/>}</P> <p> int vrandtest () <br/>{< br/> vector <char> VI; <br/> vector <char >:: iterator VP; <br/> srand (unsigned (Time (null); // This is required because it generates a random seed and the subsequent random seed will change. Otherwise, the random sequence generated each time is the same <br/> for (INT I = 0; I <10; I ++) vi. push_back (I + 'A'); <br/> for (Vp = VI. begin (); VP! = VI. end (); ++ vp) <br/> cout <* VP <""; <br/> cout <Endl; <br/> vrand <char> (Vi, myrandom); // call the template function to generate a random sequence. <br/> for (Vp = VI. begin (); VP! = VI. End (); ++ vp) <br/> cout <* VP <""; <br/> cout <Endl; <br/>}

Because templates are used in the preceding example, you can perform random sorting for various types.

The above example shows C ++. By using STL, we can simply implement random sequences, reflecting the powerful STL.

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• Sales Support

1 on 1 presale consultation

• After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.