我想写一个用随机值填充向量的函数。
T =数字和Pnt结构。
我的问题:如何使用随机值填充模板矢量?
#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来实现?
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;
}
答案 0 :(得分:3)
无需编写自己的填充方法,请使用std::generate
或std::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;
}