[英]How to use std::fill on an template type array made using make_unique<T[]>()?
I want to create class for my 2d matrix.我想为我的二维矩阵创建类。 I have used the following code我使用了以下代码
#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;
}
}
};
Now I want to replace the loops with std::fill
but somehow I am not able to do this.现在我想用std::fill
替换循环,但不知何故我无法做到这一点。 All the examples are on std::vector<T>
or on std::array<T>
.所有示例都在std::vector<T>
或std::array<T>
。 Can anyone help me with this please?任何人都可以帮我解决这个问题吗?
EDIT 1: One way as @StoryTeller - Unslander Monica mentioned is编辑 1: @StoryTeller - Unslander Monica 提到的一种方式是
std::fill(&data[0], &data[0] + row*col , def);
Is there any cleaner way?有没有更干净的方法?
std::fill
expects a pair of iterators (that could be pointers) which define a valid range. std::fill
需要一对定义有效范围的迭代器(可以是指针)。 In your case the range is from the address of the first element &data[0]
, up to one past the end &data[0] + row*col
.在您的情况下,范围是从第一个元素&data[0]
的地址到末尾&data[0] + row*col
。 Translating it into an invocation, we get将其转换为调用,我们得到
std::fill(&data[0], &data[0] + row*col , def);
or the equivalent, but in my opinion not quite as obvious:或等价物,但在我看来并不那么明显:
std::fill(data.get(), data.get() + row*col , def);
Another approach, is to let the standard library do the arithmetic itself, and use the complementary algorithm std::fill_n
.另一种方法是让标准库自己进行算术运算,并使用补充算法std::fill_n
。 Thus producing one of these options.从而产生这些选项之一。
std::fill_n(&data[0], row*col , def);
std::fill_n(data.get(), row*col , def);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.