Reputation: 357
I'm writing a class that holds a matrix (of double values), represented as vector<vector<double>>
;
I want to implement the operator=
, to re-fill my matrix with the details of a given sparse matrix. I'm writing the following code:
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;
}
Does the resize()
method fill automatically the vector with zeros?
Is my implementation ok?
Upvotes: 4
Views: 18947
Reputation: 12814
If you want to zero out the entire 2d array, you can use the assign function of vector:
v.assign(size, vector<double>(size, 0.));
This will make a 2d vector of sizeXsize filled with zeros.
In your case:
RegMatrix& RegMatrix::operator=(const SparseMatrix rhs){
if(*this != rhs){
_matrix.assign(rhs.getRow(), vector<double>(rhs.getCol(), 0.));
for(i=0;i<rhs.getSize();++i){
Element e = rhs.getElement(i);
_matrix[e._row][e._col] = e._val;
}
}
return *this;
}
Upvotes: 4
Reputation: 320531
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 your resize
calls) it normally means that the std::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
_matrix.at(i).resize(rhs.getCol());
is actually translated into
_matrix.at(i).resize(rhs.getCol(), double());
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.
Upvotes: 0
Reputation: 54158
New elements take the vector
member's default value, or a specific value if you use the overload of resize
with two parameters.
void resize(
size_type _Newsize,
Type _Val
);
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.
Upvotes: 5