将std :: list< std :: string>随机化 [英] Randomize a std::list<std::string>

查看:48
本文介绍了将std :: list< std :: string>随机化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, I have an std::list<std::string> and I'm asking if there is a function or a trick to randomize the list.

示例:

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 : "!!"

例如,我想要的是获取这样的随机列表的函数或技巧:

what I want is a function or a trick to get a random list like this for example :

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"

我认为您理解我的意思:)

I think that You understand what I mean :)

推荐答案

如果您想将 list 保留为列表,甚至不修改它,而只需提供一个随机的视图"即可.然后,您可以使用 vector< reference_wrapper< const string>> ,然后对矢量进行随机播放.这样就可以完整保留列表,使您可以在向量中看到列表的改组版本,而无需复制所有字符串.

If you want to keep your list as a list and even not modify it, but just provide a randomized "view" of it, then you can use a vector<reference_wrapper<const string>> and then shuffle the vector. This leaves the list intact, lets you see a shuffled version of it in the vector and doesn't need to copy all the strings.

例如:

#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&lt; std :: string&gt;随机化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆