C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ Algorithm shuffle()C++ Algorithm shuffle() function reorders the elements of a range by putting them at random places, using g as uniform random number generator. Syntaxtemplate <class RandomAccessIterator, class URNG> void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g); Parameterfirst: A random access iterator pointing the position of the first element in the range to be rearranged. last: A random access iterator pointing the position one past the final element in the range to be rearranged. g: A special function object called a uniform random number generator. Return valueNone ComplexityComplexity is linear in the range [first, last): obtain random values and swaps elements. Data racesThe object in the range [first, last) are modified. ExceptionsThis function throws an exception if any of random number generations, the element swaps or an operation on iterator throws an exception. Please note that invalid parameters cause an undefined behavior. Example 1Let's see the simple example to demonstrate the use of shuffle(): #include <iostream> // std::cout #include <algorithm> // std::shuffle #include <array> // std::array #include <random> // std::default_random_engine #include <chrono> // std::chrono::system_clock using namespace std; int main () { array<int,5> foo {1,2,3,4,5}; // obtain a time-based seed: unsigned seed = chrono::system_clock::now().time_since_epoch().count(); shuffle (foo.begin(), foo.end(), default_random_engine(seed)); cout << "shuffled elements:"; for (int& x: foo) cout << ' ' << x; cout << '\n'; return 0; } Output: shuffled elements: 4 1 3 5 2 Example 2Let's see another simple example: #include <random> #include <algorithm> #include <iterator> #include <iostream> using namespace std; int main() { vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; random_device rd; mt19937 g(rd()); shuffle(v.begin(), v.end(), g); copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << "\n"; return 0; } Output: 8 6 10 4 2 3 7 1 9 5 Example 3Let's see another simple example: #include <algorithm> #include <iostream> #include <vector> #include <numeric> #include <iterator> #include <random> using namespace std; int main() { vector<int> v(10); iota(v.begin(), v.end(), 0); cout << "before: "; copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << endl; random_device seed_gen; mt19937 engine(seed_gen()); shuffle(v.begin(), v.end(), engine); cout << " after: "; copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << endl; return 0; } Output: before: 0 1 2 3 4 5 6 7 8 9 after: 4 3 1 2 7 0 8 9 6 5
Next TopicC++ Algorithm
|