c++ - 随机化一个 std::list<std::string>

标签 c++ list

所以,我有一个 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作为一个列表,甚至不修改它,只是提供它的随机“ View ”,然后你可以使用 vector<reference_wrapper<const string>>然后打乱 vector 。这会使列表保持原样,让您可以在 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

关于c++ - 随机化一个 std::list<std::string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38156261/

相关文章:

c++ - 在定义之前显式实例化模板函数

c - 如何从 C 列表中删除值 a 并按元素搜索?

c++ - Lambda:未评估上下文中未捕获的对象

c++ - SFINAE 或 enable_if 检查非类型模板参数是偶数还是奇数

python - 在 python 中使用列表中的 bool 值调用字符串

html - 将 li 直线向下对齐

string - Haskell:从字符串列表中删除空格

C++ 删除列表中的元音 <string>

c++ - 这里有什么方法可以使用拉普拉斯算子找出图像是否模糊

C++ nlohmann/json 如何使用运行时提供的 json_pointers 来读取 json 值