随机访问矢量 [英] Random Access for Vector
问题描述
我有一个在C ++中有一个排序数据的向量,我想以随机顺序访问数据,用于混洗数据。 rand的问题是可以同时访问两个索引,并且当最后一个项目保留时,会有很多不需要的查找。任何建议。
I have a vector in C++ that has sorted data, I want to access the data in random order for shuffling the data. The problem with rand is that two indexes can be accessed at the same time and also when the last item remains there will be a lot of un-needed lookups. Any suggestions.
推荐答案
您可以简单地使用 std :: shuffle
,其存在于< algorithm>
中。它使用指向第一个位置的一个迭代器来考虑进行混排,指向要考虑进行混排的最后一个位置的迭代器和一个RNG引擎。在下面的示例中,我将使用< random>
中的 std :: default_random_engine
。
You can simply shuffle the array with std::shuffle
, which exists in <algorithm>
. It takes the an iterator pointing to the first position to be considered for shuffling, an iterator pointing to the last position to be considered for shuffling, and a RNG engine. In the following example, I'll use std::default_random_engine
found in <random>
.
#include <iostream>
#include <algorithm>
#include <random>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4, 5, 6};
auto rng = std::default_random_engine{};
std::shuffle(std::begin(v), std::end(v), rng);
for(auto&& e: v) {
std::cout << e << " ";
}
std::cout << '\n';
}
当我运行这个时,我得到:
When I run this, I got:
3 1 5 6 2 4
没有关于如何实现 std :: shuffle
的细节,但很可能是 O(n)
shuffle算法,如Fisher-Yates(Knuth)Shuffle,因此不会有很多不需要查找。
There are no details on how std::shuffle
is implemented, but it's very likely an O(n)
shuffle algorithm like the Fisher-Yates (Knuth) Shuffle, so there won't be many "unneeded" lookups.
这篇关于随机访问矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!