矢量resize()自动填充
我正在编写一个包含(双精度值)矩阵的类,表示为 vector
;
我想实现operator=,用给定稀疏矩阵的详细信息重新填充我的矩阵。我正在编写以下代码:
RegMatrix& RegMatrix::operator=(const SparseMatrix rhs){
if(*this != rhs){
_matrix.clear();
_matrix.resize(rhs.getRow());
int i;
for(i=0;i<rhs.getRow();++i){
_matrix.at(i).resize(rhs.getCol());
}
for(i=0;i<rhs.getSize();++i){
Element e = rhs.getElement(i);
_matrix[e._row][e._col] = e._val;
}
}
return *this;
}
resize()
方法是否自动用零填充向量?
我的实现没问题吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
新元素采用
vector
成员的默认值,或者如果您使用带有两个参数的resize
重载,则采用特定值。在您的情况下,默认值将是一个空的
vector
- 如果这不是您想要的,请将您想要放置的内容传递给上面的重载。现有元素不会被修改。
New elements take the
vector
member's default value, or a specific value if you use the overload ofresize
with two parameters.In your case, the default will be an empty
vector<double>
- if that is not what you want, pass what you DO want to put there to the overload above.Existing elements are not modified.
如果你想将整个二维数组归零,可以使用vector的赋值函数< /a>:
这将使 sizeXsize 的二维向量用零填充。
在你的情况下:
If you want to zero out the entire 2d array, you can use the assign function of vector:
This will make a 2d vector of sizeXsize filled with zeros.
In your case:
所有
std::vector
方法都不会在内部使用任何形式的默认初始化。std::vector<>
仅要求其元素可CopyConstructible 和Assignable,但不要求它们DefaultConstructible< /em>。每当您遇到某些元素似乎是“无中生有”构造的情况(就像您的resize
调用的情况)时,通常意味着std::vector<> ;
您使用的方法有一个额外的参数,它允许您传递将复制构造新元素的值。我们通常不会注意到这一点,因为这些参数总是提供等于相应类型的()
初始化元素的默认值。在您的例子中,
实际上被翻译为
调用,这意味着正式地是您隐式传递新元素的初始值。
double()
的计算结果为零,所以是的,列向量最初将用零填充。None of
std::vector<>
methods ever use any form of default initialization internally.std::vector<>
only requires its elements to be CopyConstructible and Assignable, but does not require them to be DefaultConstructible. Every time you run into a situation when some elements seem to be constructed "out of nothing" (as is the case with yourresize
calls) it normally means that thestd::vector<>
method you are using has an extra parameter, which allows you to pass the value from which the new elements will be copy-constructed. We don't often notice that, since these arguments are always supplied with default values equal to the()
-initailized element of the corresponding type.In your case, the
is actually translated into
call, meaning that formally it is you who's implicitly passing the initial value for the new elements.
double()
evaluates to zero, so yes, the column vectors will be filled with zeros initially.