如何使用随机数创建 n 个随机大小的列表?

时间:2021-05-11 08:47:44

标签: c++

问题如下:

我想创建 k 个列表,其中 k 由用户输入。每个列表的大小将是一个从 100 到 200 的随机数。然后,每个列表将填充从 0 到 50 的随机数。

例如,如果用户输入 2 作为将创建的列表数 k,我将不得不创建 2 个随机大小不小于 100 且不超过 200 的列表。假设第一个随机大小是120 和第二个 150。然后,我必须用 0 到 50 的 120 个随机数填充第一个列表,用 0 到 50 的 150 个随机数填充第二个列表。这是我想到的,但肯定有几个错误我不明白。

#include <iostream>
#include <random>
#include <functional>

using namespace std;

void output() {

};

int main() {

    int k;
    cout << "What is the number k of lists?" << endl;
    cin >> k;

    //I googled this part to generate random numbers
    random_device rd; // obtain a random number from hardware
    mt19937 gen(rd()); // seed the generator
    uniform_int_distribution<int> list_size_distribution(100, 200);
    uniform_int_distribution<int> data_element_distribution(0, 50);

    auto random_list_size = bind(list_size_distribution, gen);
    auto random_element = bind(data_element_distribution, gen);

    int lists[k][200];
    
    //I thought of maybe creating k amount of lists with a size of 200 and fill everything with -1 at the 
    //start?
    for (int i=0; i<k; i++) {
        for (int j=0; j<200; j++) {
            lists[k][j] = -1;
        }
    }

    //Something is terribly wrong here for sure
    for (int i=0; i<k; i++) {
        for (int j=0; j<random_list_size(); j++) {
            lists[i][j] = random_element();

            //Print everything to see if it's correct
            cout << lists[i][j] << ' ';
        }
        cout << "END OF LIST" << endl;
    }
}

2 个答案:

答案 0 :(得分:3)

我建议使用 std::generate 生成值,并将它们存储在 std::vector

#include <iostream>
#include <random>
#include <functional>
#include <vector>
#include <algorithm>

int main() {

    int k;
    std::cout << "What is the number k of lists?" << std::endl;
    std::cin >> k;

    //I googled this part to generate random numbers
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<int> list_size_distribution(100, 200);
    std::uniform_int_distribution<int> data_element_distribution(0, 50);

    auto random_list_size = std::bind(list_size_distribution, gen);
    auto random_element = std::bind(data_element_distribution, gen);

    auto generate_vector = [&](){
        std::vector<int> vec(random_list_size()); // create a vector with random number of elements
        std::generate(vec.begin(), vec.end(), random_element); // assign each element
        return vec;
    }
    
    std::vector<std::vector<int>> lists(k); // create k vector<int>s
    std::generate(lists.begin(), lists.end(), generate_vector); // assign each element

    for (auto & list : lists) {
        for (auto val : list) {
            std::cout << val << ' ';
        }
        std::cout << "END OF LIST" << std::endl;
    }
}

答案 1 :(得分:0)

cin >> k;
// ...
int lists[k][200];

数组变量的大小必须是 C++ 中的编译时常量。 k 不是编译时间常数,因此程序格式错误。必须动态分配数组才能使用动态大小。例如,您可以使用 std::vector