Suppose you need to specify a random number in the range. The traditional method is to use the anss C function random () and format the result so that the result falls within the specified range. However, using this method has at least two disadvantages. First, the result is often distorted during formatting, so the correct random number is not obtained (for example, the frequency of some numbers is higher than other numbers ). Secondly, random () only supports integer data. It cannot be used to generate random characters, floating-point numbers, strings or records in the database. For the above two problems, C ++ provides a better solution, that is, the random_shuffle () algorithm. Don't worry. I will show you how to use this algorithm to generate different types of random numbers. The best way to generate a random element set within a specified range is to create an ordered sequence (that is, a vector or a built-in array) that contains all values in the specified range. For example, if you need to generate 100 numbers between 0 and 99, create a vector and fill the vector with 100 numbers in ascending order:# Include <vector> Using STD: vector; Int main () { Vector <int> VI; For (INT I = 0; I <10; I ++) Vi. push_back (I ); /* Now the vector contains 100 integers ranging from 0 to 99 in ascending order */ } After filling the vector, use the random_shuffle () algorithm to disrupt the order of elements. Random_shuffle () is defined in the standard header file <algorithm. h>. Because All STL algorithms are declared in the namespace STD:, so pay attention to correct data types. Random_shuffle () has two parameters. The first parameter is the iterator pointing to the first element of the sequence, and the second parameter is pointing to the next position of the last element of the sequence. The following code segment uses the random_shuffle () algorithm to disrupt elements previously filled in the vector:# Include <algorithm> Using STD: random_shuffle; Random_shuffle (VI. Begin (), VI. End ();/* disrupt elements */ If you want to check the disrupted elements, you can use the following method to check the storage order after they are disrupted:For (INT I = 0; I <100; I ++) Cout <VI [I];/* display elements in disordered Order */ Random_shuffle () is a completely common algorithm-applicable to built-in data types and user-defined types. In the following example, a vector with seven string objects is created, which contains the days of a week and uses random_shuffle () to disrupt their order:# Include <string> # Include <vector> # Include <algorithm> # Include <iostream> Using namespace STD; Int main () { Vector <string>; Vs. push_back (string ("Sunday ")); Vs. push_back (string ("Monday ")); ... Vs. push_back (string ("Saturday ")); Random_shuffle (vs. Begin (), vs. End ();/* disrupt the order */ For (INT I = 0; I <7; I ++) Cout <vs [I];/* display elements after disordered Order */ } How to Use random_shuffle () to process built-in Arrays |