用随机值填充一个通用向量

Filling a generic vector with random values

本文关键字:一个 向量 随机 填充      更新时间:2023-10-16

我想写一个函数,用随机值填充一个向量。

T = number and Pnt struct。

我的问题:我如何用随机值填充模板向量?

#include <vector>
using namespace std;
class  Pnt{
public:
    int x, y;
    Pnt(int _x, int _y) :x(_x), y(_y){}
};
template <typename T>
void fill(vector<T>& vec){
   for (auto& value : vec)
    // how to fill with random values
}
int main() {
    vector<Pnt> arr_pnt(10);
    fill(arr_pnt);
    vector<int> arr_int(10);
    fill(arr_int);
    return 0;
}
编辑:

我已将代码修改如下所示。是否有一种方法可以通过std::is_same在fill函数中实现?

class  Pnt{
public:
    int x, y;
    Pnt(int _x, int _y) :x(_x), y(_y){}
};
void getRnd(Pnt& p){
    p.x = rand();
    p.y = rand();
}
void getRand(int& value){
    value = rand();
}
template <typename T>
void fill(vector<T>& vec){
    for (auto& value : vec)
    getRand(value);

}
int main() {
    vector<Pnt> arr_pnt(10);
    fill(arr_pnt);
    vector<int> arr_int(10);
    fill(arr_int);
    return 0;
}

无需编写自己的填充方法,使用std::generatestd::generate_n即可。

// use of std::rand() for illustration purposes only
// use a <random> engine and distribution in real code
int main() {
    vector<Pnt> arr_pnt(10);
    std::generate(arr_pnt.begin(), arr_pnt.end(), [](){ return Pnt{std::rand(), std::rand()};});
    vector<int> arr_int;
    std::generate_n(std::back_inserter(arr_int), 10, std::rand);
    return 0;
}