我正在实现的 fwd_iterator 有一个很奇怪的问题:
如果我在类内部定义的方法中使用迭代器,它们会起作用,但如果我创建一个使用迭代器的全局范围的方法,valgrind 会说我正在尝试访问未初始化的内存。
似乎在类外部创建的迭代器无法读取类的私有(private)属性(即使使用创建的公共(public)方法来执行此操作)。
这是全局范围的方法:
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;
}
这是内部类方法:
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;
}
已解决:迭代器类有两个属性,value_type val 和 sm,一个指向类本身的指针。在 operator=(const iterator& other) 我忘记在 val=other.val 之后添加; sm=other.sm;行。
现在一切正常!
最佳答案
迭代器类有两个属性,value_type val 和 sm,一个指向类本身的指针。在 operator=(const iterator& other) 我忘记在 val=other.val 之后添加; sm=other.sm;行。
现在一切正常!
关于c++ - 使用大小为 8 的未初始化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9214853/