簡體   English   中英

隨機化一個 std::list<std::string>

[英]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>> ,然后對向量進行洗牌。 這使列表保持完整,讓您可以在向量中看到它的混洗版本,而無需復制所有字符串。

例如:

#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來提高效率,但我將把它留給您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM