函数模板未正确生成随机数

1 c++ random templates vector

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

代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 5

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

改变:

template<class T, class B>void genRand(T data, B size)
Run Code Online (Sandbox Code Playgroud)

到:

template<class T, class B>void genRand(T &data, B size)
                                       ^^^^^^^
Run Code Online (Sandbox Code Playgroud)