C++ shuffle()
C++算法shuffle()
C++算法 shuffle()函数通过将g均匀地放置在随机位置来重新排列范围的元素随机数生成器。
语法
template <class RandomAccessIterator, class URNG>
void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);
参数
first: 一个随机访问迭代器,指向要重排范围内第一个元素的位置。
last: 一个随机访问迭代器,该位置指向要重排范围中最后一个元素之后的位置。
g : 一个称为统一随机数生成器的特殊功能对象。
返回值
无
复杂度
复杂度在[first,last)范围内是线性的: 获取随机值并交换元素。
数据竞争
在[first,last)范围内的对象被修改。
异常
如果随机数生成,元素交换或迭代器上的任何操作抛出异常,则此函数将引发异常。
请注意,无效参数会导致未定义的行为。
示例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
示例2
让我们看另一个简单的示例:
#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;
}
输出:
示例3
让我们看另一个简单的示例:
#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