I'm having a quite strange problem with the fwd_iterator that I'm implementing:
if I use the iterators in methods defined inside the class, they work, but if I create a method with global scope in which I use iterators, valgrind says that I'm attempting to access to uninitialised memory.
It seems like iterators created outside the class cannot read a private attribute of the class (even with public methods created to do this).
This is the global-scope method:
template<typename T, class Pred>
int evaluate(SparseMatrix<T> &sm, Pred pred){
typename SparseMatrix<T>:: iterator begin, end;
int count=0;
begin=sm.begin();
end=sm.end();
while(begin!=end){
if(pred(*(begin->data))) count++;
begin++;
}
int dcount=0;
if(pred(sm.getDef())) dcount = ((sm.getRows() * sm.getCols()) - sm.getSize());
return count+dcount;
}
This is the inside-class method:
void print_it() {
iterator x=begin();
iterator y=end();
int i=1;
while(x!=y){
cout<<i<<".("<<(x->i)<<","<<(x->j)<<")="<<*(x->data)<<endl;
++x;
i++;
}
if(x==y) cout<<"End."<<endl;
cout<<endl;
}
Solved: iterator class has two attributes, value_type val, and sm, a pointer to the class itself. In operator=(const iterator& other) I forgot to add after val=other.val; the sm=other.sm; line.
Now everything works!