vendredi 19 août 2022

How to generate vector of vectors of random sizes having random number of uint8_t type within range? [duplicate]

I want to create vector of vectors of random sizes having random number of uint8_t type within range eg 0 to 19.

This is my function for generating the same it works for int type but fails for uint8_t.

#include <cstring>
#include <sstream>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <vector>
#include <time.h>

void generate_random_vectors(const int num_of_rand_vectors, std::vector<std::vector<uint8_t>> &vec)
{
    for (int j = 0; j < num_of_rand_vectors; ++j)
    {
        // the vector size will be randomal: between 0 to 19
        int vec_size = (rand() % 20);
        std::vector<uint8_t> rand_vec(vec_size);
        for (int k = 0; k < vec_size; ++k)
        {
            // each vec element will be randomal: between 1 to 20
            rand_vec[k] = 1 + (rand() % 20);
        }
        // each vector will be sorted if you want to
        // push each of the 'num_of_rand_vectors'-th vectors into vec
        vec.push_back(rand_vec);
    }
}

Usage

std::vector<std::vector<uint8_t>> vec;
generate_random_vectors(3, vec);

for (int i = 0; i < vec.size(); i++)
{
    for (int j = 0; j < vec[i].size(); j++)
    {
        std::cout << vec[i][j] << " ";
    }
    std::cout << "\n";
}

Error output:

 ♥ ♫ ♠ ♠ ♣ ♥ ♥
 ♫ ♂ ‼ ☻ ☼ ☻
♀ ♀ ♀
 ♠  ☻ ♂ ♫ ☼ ‼ ¶

How could I correctly implement it?




Aucun commentaire:

Enregistrer un commentaire