随机化一个标准::列表<标准::字符串>
Randomize a std::list<std::string>
所以,我有一个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
来使它更有效,但我将把它留给您。
相关文章:
- 使用CMake检测支持的C++标准
- 如何理解C++标准N3337中的expr.const.cast子句8
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 呼叫运营商<<临时
- 编译标准库类型
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 铸造标准::有没有回到原来的类型
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 标准库类型的赋值运算符的引用限定符
- 标准是否严格定义了该程序应该如何编译?
- 如何从Windows应用程序输出到标准?
- 安全到标准:移动会员?
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 这是否符合C++标准:双响双响,例如!!(-0.0).
- C++标准::cout和<<操作员,优先级