Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector resize() automatic fill

Tags:

c++

vector

resize

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?

like image 758
limlim Avatar asked Feb 26 '23 02:02

limlim


1 Answers

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.

like image 149
Steve Townsend Avatar answered Mar 06 '23 20:03

Steve Townsend