Reputation: 305
I want write a function that fill a vector with random values.
T = numerical and Pnt struct.
My Question : How do I fill a vector of template with random values?
#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;
}
Edit:
I have modified the code as shown below.Is there a way to do it by std::is_same inside the fill function?
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;
}
Upvotes: 0
Views: 279
Reputation: 137425
No need to write your own fill method, use std::generate
or 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;
}
Upvotes: 3