我正在做一个 main.cpp 来测试我对稀疏矩阵的实现,我在其中创建了两个 const_iterator:
SparseMatrix<double>::const_iterator a,b;
a=mata.begin(); //mata previously created as SparseMatrix<double>
b=mata.end();
... //code goes on
问题是它不调用 begin 和 end (它甚至不做初始 cout),但如果我创建两个迭代器,它就可以工作。这是我为 const_iterators 实现 begin 和 end 的方式。
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;
}
我注意到的一件奇怪的事情是,如果我在 SparseMatrix 的类方法中创建两个 const_iterators,它们就可以工作。