用随机数填充向量 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21516575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:40:51  来源:igfitidea点击:

Fill a vector with random numbers c++

c++randomvectorsrand

提问by Valrok

I've got a vector that I'm trying to fill up with random numbers. I keep running into an issue however that the vector mostly outputs 0 each time that I'm running it (it shouldn't output a 0 ever). What am I doing wrong in my code written below to make it output 0 (it outputs 0 more so than any other number):

我有一个我试图用随机数填充的向量。我一直遇到一个问题,但是每次我运行向量时,它大多输出 0(它不应该输出 0)。我在下面编写的代码中做错了什么以使其输出 0(它输出 0 比任何其他数字都多):

vector<int> myVector;
srand((unsigned)time(NULL));
int a = rand() % 20 + 1; //1 to 20    
for (int i =0; i < a; i++){
        int b = rand() % 20 + 1;
        myVector.push_back(b);
        cout << myVector[b] << endl;
    }

I am a beginner and have not done much C++ programming in a long time so I'm not sure what is making my code malfunction. If someone could explain what I've done wrong it would be greatly appreciated.

我是初学者,很长一段时间没有做过很多 C++ 编程,所以我不确定是什么导致我的代码出现故障。如果有人能解释我做错了什么,将不胜感激。

采纳答案by Serdalis

You are calling the wrong index in your vector

您在向量中调用了错误的索引

Try doing:

尝试做:

cout << myVector[i] << endl;

else you will risk running off the end of your vertex for the first 20 or so iterations.

否则,在前 20 次左右的迭代中,您将冒着跑掉顶点的风险。

You can also call .back()on your vector to get the last item in the vector.

您还可以在向量上调用.back()以获取向量中的最后一项。

回答by Marko Tunjic

You can use std::generate algorithm to fill a vector of n elements with random numbers.

您可以使用 std::generate 算法用随机数填充 n 个元素的向量。

In modern C++ it's recommended not to use any time-based seeds and std::rand, but instead to use random_device to generate a seed. For software-based engine, you always need to specify the engine and distribution. Read More..

在现代 C++ 中,建议不要使用任何基于时间的种子和 std::rand,而是使用 random_device 生成种子。对于基于软件的引擎,您始终需要指定引擎和发行版。 阅读更多..

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

using namespace std;

int main()
{
    // First create an instance of an engine.
    random_device rnd_device;
    // Specify the engine and distribution.
    mt19937 mersenne_engine {rnd_device()};  // Generates random integers
    uniform_int_distribution<int> dist {1, 52};

    auto gen = [&dist, &mersenne_engine](){
                   return dist(mersenne_engine);
               };

    vector<int> vec(10);
    generate(begin(vec), end(vec), gen);

    // Optional
    for (auto i : vec) {
        cout << i << " ";
    }


}

If you want to rearrange the elements of a range in a random order:

如果要以随机顺序重新排列范围的元素:

  std::shuffle(begin(vec), end(vec), mersenne_engine);

回答by Martin.Martinsson

What about simply:

简单地说:

std::vector<int> v(1000);
std::generate(v.begin(), v.end(), std::rand);

回答by Marek Kurdej

Just adding my 2 cents... This response is similar to the one given by Marko Tunjic, but it doesn't use std::randfrom C, but C++11 features instead. It allows you to use the distribution of your choice, uniform_int_distributionin the example below.

只需添加我的 2 美分...此响应类似于Marko Tunjic给出的响应,但它不使用std::randC,而是使用 C++11 功能。它允许您使用您选择的发行版,uniform_int_distribution在下面的示例中。

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

static std::vector<int> generate_data(size_t size)
{
    using value_type = int;
    // We use static in order to instantiate the random engine
    // and the distribution once only.
    // It may provoke some thread-safety issues.
    static std::uniform_int_distribution<value_type> distribution(
        std::numeric_limits<value_type>::min(),
        std::numeric_limits<value_type>::max());
    static std::default_random_engine generator;

    std::vector<value_type> data(size);
    std::generate(data.begin(), data.end(), []() { return distribution(generator); });
    return data;
}

int main()
{
    for (auto i = 0u; i < 5; ++i)
    {
        std::vector<int> myVector = generate_data(10);
        myVector = generate_data(10);

        std::cout << "myVector (iteration " << i << "): ";
        for (auto v: myVector)
        {
            std::cout << v << ",";
        }
        std::cout << "\n";
    }
}

回答by Khalil Ismail

You are calling the wrong index in your vector

您在向量中调用了错误的索引

cout << myVector[i] << endl;

回答by Sanjaya R

Its not clear what you are trying to do with the loop, the code is creating a vector of random size, filled with random numbers.

不清楚你想用循环做什么,代码正在创建一个随机大小的向量,填充随机数。

You are outputting "myVector[b]", but 'b' is the random value, not the index of just added number. You could just :

您正在输出“myVector[b]”,但“b”是随机值,而不是刚刚添加的数字的索引。你可以:

cout << b << endl;

But really you should size the vector, and just access by index.

但实际上您应该调整向量的大小,并且只需按索引访问。

int vec_size = rand() % 20 + 1;
vec<int> myvec(vec_size);
for( int i = 0; i < vec_size; ++i ) {
    vec[i] = rand() % 20 + 1;
}

/* output the list after you made it */
std::copy(myvec.begin(), myvec.end(),
        std::ostream_iterator<int>(cout, "\n"));

回答by Giroud Vren

// here I generate a vector that contains random vectors
// for example, after this code, vec = { {1,4,8}, {1,3,6,7,9}, {2,5,6} }

#include <vector>
#include <time.h>

void generate_random_vectors(const int num_of_rand_vectors, vector<vector<int>> &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);
        vector<int> 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
        sort(rand_vec.begin(), rand_vec.end());
        // push each of the 'num_of_rand_vectors'-th vectors into vec
        vec.push_back(rand_vec);
    }
}

void main() {

    srand(static_cast<unsigned int>(time(NULL)));

    // input vector containing random sorted vectors
    vector<vector<int>> vec;
    generate_random_vectors(3, vec);
}

回答by Tony Lim

cout << myVector[b] ?!

it should be : cout << myVector[i];

它应该是 : cout << myVector[i];