随机化一个标准::列表<标准::字符串>

Randomize a std::list<std::string>

本文关键字:标准 lt 字符串 gt 列表 一个 随机化      更新时间:2023-10-16

所以,我有一个std::list<std::string>,我问是否有一个函数或技巧来随机化列表。

的例子:

first elem of the list : "Hello"
second elem of the list : "Stack"
third elem of the list : "Over"
fourth elem of the list : "Flow"
fifth elem of the list : "!!"

我想要的是一个函数或一个技巧来获得一个随机列表,比如:

first elem of the list : "Flow"
second elem of the list : "!!"
third elem of the list : "Hello"
fourth elem of the list : "Stack"
fifth elem of the list : "Over"

我认为你明白我的意思:)

如果你想保持你的list作为一个列表,甚至不修改它,而只是提供一个随机的"视图";然后你可以使用vector<reference_wrapper<const string>>,然后对向量进行洗牌。这使列表保持完整,让您可以在vector中看到它的洗牌版本,并且不需要复制所有字符串。

例如:

#include <iostream>
#include <functional>
#include <iterator>
#include <algorithm>
#include <string>
#include <list>
#include <vector>
#include <random>
int main() {
    std::list<std::string> l{"Hello", "Stack", "Over", "flow", "!!"};
    std::vector<std::reference_wrapper<const std::string>> v(l.cbegin(), l.cend());
    std::random_device rd;
    std::mt19937 generator(rd());
    std::shuffle(v.begin(), v.end(), generator);
    std::cout << "Original list:n";
    std::copy(l.cbegin(), l.cend(), std::ostream_iterator<std::string>(std::cout, " "));
    std::cout << "nShuffled view:n";
    std::copy(v.cbegin(), v.cend(), std::ostream_iterator<std::string>(std::cout, " "));
}

示例输出:

Original list:
Hello Stack Over flow !! 
Shuffled view:
Hello Over !! Stack flow 

实例:https://ideone.com/a1LIyh

正如人们所提到的,在这种情况下使用std::list是相当奇怪的-实际上,您应该使用像std::vector这样的东西,它几乎总是能更好地完成相同的工作。

然而,对于您的情况,最简单的"非解决方案"是将列表复制到std::vector,使用std::random_shuffle,然后再复制回来:

// get some data
std::list<std::string> data = getData();
// copy it into a vector and shuffle it
std::vector<std::string> temp(data.begin(), data.end());
std::random_shuffle(temp.begin(), temp.end());
// copy the (shuffled) vector back into the list
std::copy(temp.begin(), temp.end(), data.begin());

不可否认,由于在两个方向上复制整个数据集,它并不是那么有效,但对于您的目的来说,它应该是好的。如果您愿意,您可以通过移动数据而不是使用std::vector构造函数和std::copy来使它更有效,但我将把它留给您。