C++算法 shuffle()函数使用g作为统一的随机数生成器,通过将参数中的元素放置在随机位置来对它们进行重新排序。
template <class RandomAccessIterator, class URNG> void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);
first:一个随机访问迭代器,指向要重新排列的参数内第一个元素的位置。
last:一个随机访问迭代器,该位置指向要重排参数中最后一个元素之后的位置。
g :一种特殊函数对象,称为统一随机数生成器。
没有
让我们看一个简单的示例来演示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; }
输出:
shuffled elements: 4 1 3 5 2
让我们看另一个简单的例子:
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-algorithm-shuffle-function.html
来源:LearnFk无涯教程网
#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; }
输出:
8 6 10 4 2 3 7 1 9 5
让我们看另一个简单的例子:
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-algorithm-shuffle-function.html
来源:LearnFk无涯教程网
#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; }
输出:
before: 0 1 2 3 4 5 6 7 8 9 after: 4 3 1 2 7 0 8 9 6 5
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)