【问题标题】:Function template isn't producing random numbers properly函数模板未正确生成随机数
【发布时间】:2014-10-18 09:30:11
【问题描述】:

我有一个函数模板,它应该接受一个向量并在其中生成随机数。但是,当我打印整个向量时,它都是零。

代码:

const  int smallSize = 20;

// declare small vector
vector <int> smallVector(smallSize);

genRand(smallVector, smallSize);

// make copy of small vector 
vector<int> copySmallVector = smallVector;

// function template for generating random numbers
template<class T, class B>void genRand(T data, B size)
{
    for (B i = 0; i < size; i++)
    {
        data[i] = (1 + rand() % size);
    }
}

【问题讨论】:

  • 您是否致电srand() 将随机引擎播种到任何地方?
  • 我添加,srand 进入我的主要,我继续得到所有 0 的随机生成
  • Paul R 的回答是正确的,虽然调用srand() 应该做一次。
  • 考虑generate(myvec.begin(), myvec.end(), rand);

标签: c++ templates random vector


【解决方案1】:

您正在向量的副本中生成随机数,然后在函数返回时将其丢弃。

变化:

template<class T, class B>void genRand(T data, B size)

到:

template<class T, class B>void genRand(T &data, B size)
                                       ^^^^^^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    相关资源
    最近更新 更多