Strange const_iterator behavior
-
27-04-2021 - |
Question
I'm doing a main.cpp to test my implementation of a sparse matrix, where I create two const_iterators:
SparseMatrix<double>::const_iterator a,b;
a=mata.begin(); //mata previously created as SparseMatrix<double>
b=mata.end();
... //code goes on
The problem is that it doesn't call begin and end (it doesn't even do the initial cout), but if I create two iterators it works. Here's how I implemented begin and end for const_iterators.
const_iterator begin() const
{
cout<<"Begin"<<endl;
int minr=minRow();
int minc=minCol(findRow(minr));
mcol * mc=findCol(findRow(minr),minc);
const_iterator x;
if(mc!=NULL)
{
T* dato=&(mc->data);
x= const_iterator(genElement(minr,minc,dato));
}
else
{
x=const_iterator(NULL);
}
x.setSM(const_cast<SparseMatrix<T>*>(this));
return x;
}
const_iterator end() const
{
cout<<"End"<<endl;
const_iterator x= const_iterator(NULL);
x.setSM(const_cast<SparseMatrix<T>*>(this));
return x;
}
A strange thing I noticed is that if I create two const_iterators inside a SparseMatrix's class method, they work.
Solution
As you say, "mata
[sic] previously created as SparseMatrix<double>
", but your begin
and end
that you show are marked const
. For those const
member functions to be called, the object meta
must be const
, else the non-const
versions of begin
and end
will be called.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow