如何在使用 make_unique<T[]>() 制作的模板类型数组上使用 std::fill?
How to use std::fill on an template type array made using make_unique<T[]>()?
我想为我的二维矩阵创建类。我使用了以下代码
#include <memory>
#include <algorithm>
template <typename T>
class Matrix {
private:
int row{};
int col{};
std::unique_ptr<T[]> data; // We are going to store data into a 1d array
public:
explicit Matrix(int row, int col, T def) {
// Creates a T type matrix of row rows and col columns
// and initialize each element by def
this->row = row;
this->col = col;
this->data = std::make_unique<T[]>(row*col);
for(int i=0; i<row*col; i++) {
data[i] = def;
}
}
void setValues(T value) {
// Set the value in all the elements
for (int i=0; i<row*col; i++) {
data[i] = value;
}
}
};
现在我想用std::fill
替换循环,但不知何故我无法做到这一点。所有示例都在std::vector<T>
或std::array<T>
上。谁能帮我解决这个问题?
编辑1:一种方式作为@StoryTeller - 不诽谤莫妮卡提到是
std::fill(&data[0], &data[0] + row*col , def);
有没有更清洁的方法?
std::fill
需要一对定义有效范围的迭代器(可以是指针(。在您的情况下,范围是从第一个元素的地址&data[0]
,到结束&data[0] + row*col
的一个。将其转换为调用,我们得到
std::fill(&data[0], &data[0] + row*col , def);
或等效的,但在我看来并不那么明显:
std::fill(data.get(), data.get() + row*col , def);
另一种方法是让标准库自己做算术,并使用互补算法std::fill_n
。从而产生这些选项之一。
std::fill_n(&data[0], row*col , def);
std::fill_n(data.get(), row*col , def);
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 如何在使用 make_unique<T[]>() 制作的模板类型数组上使用 std::fill?