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