如何在使用 make_unique<T[]>() 制作的模板类型数组上使用 std::fill?

How to use std::fill on an template type array made using make_unique<T[]>()?

本文关键字:类型 fill std 数组 gt unique make lt      更新时间:2023-10-16

我想为我的二维矩阵创建类。我使用了以下代码

#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);