C++ 算法 中的 shuffle函数

首页 / C++入门教程 / C++ 算法 中的 shuffle函数

C++算法 shuffle()函数使用g作为统一的随机数生成器,通过将参数中的元素放置在随机位置来对它们进行重新排序。

shuffle - 语法

template <class RandomAccessIterator, class URNG>
  void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);

shuffle - 参数

first:一个随机访问迭代器,指向要重新排列的参数内第一个元素的位置。

last:一个随机访问迭代器,该位置指向要重排参数中最后一个元素之后的位置。

g :一种特殊函数对象,称为统一随机数生成器。

shuffle - 返回值

没有

shuffle - 例子1

让我们看一个简单的示例来演示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

shuffle - 例子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

shuffle - 例子3

让我们看另一个简单的例子:

链接: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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

邱岳的产品手记 -〔邱岳〕

邱岳的产品实战 -〔邱岳〕

玩转Spring全家桶 -〔丁雪丰〕

摄影入门课 -〔小麥〕

说透敏捷 -〔宋宁〕

NLP实战高手课 -〔王然〕

高楼的性能工程实战课 -〔高楼〕

说透数字化转型 -〔付晓岩〕

云原生架构与GitOps实战 -〔王炜〕

好记忆不如烂笔头。留下您的足迹吧 :)