用随机值填充一个通用向量
Filling a generic vector with random values
我想写一个函数,用随机值填充一个向量。
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::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;
}
相关文章:
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为什么一个向量上的多线程操作很慢
- 将一个向量插入另一个向量的某个位置
- 将指向给定子类的指针从一个向量复制到另一个向量
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 如何按另一个向量的方向调整一个向量?
- 将字符向量复制到另一个向量
- 制作一对共享指针并推送一个向量
- 你能把一个向量<int64>投射到一个向量<uint8>吗
- 大家好,当一个类有一个向量作为它的数据成员时,为什么它的大小总是24?
- 为什么我们需要在优先级队列声明中添加一个向量作为参数?
- 如何将所有指针从一个向量移动到另一个向量?
- 将一个向量映射到不同的对,即使向量映射到每对时是不同的?
- 生成一个类Name_class并将两种数据类型存储在一个向量中
- 使用步骤c++构建一个向量
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 将一个向量对放在一个无序映射与一个映射中