c++ - 使用大小为 8 的未初始化值

标签 c++ iterator sparse-matrix initialization

我正在实现的 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/

相关文章:

r - 在自定义 R 包中使用 "Matrix"包方法

r - 如何 reshape 数据帧并将其转换为 dgCMatrix?

c++ - 调用boost.asio的异步函数时何时创建线程?

java - 如何阻止迭代器跳过第一个输入的值?

java - 使用 Guava Iterables 时将使用什么 Iterable

c++ - 通过迭代器访问另一个 vector 内的 vector 元素?

c++ - 如何编写用于选择函数的样板代码

c++ - 如何避免 PANTHEIOS_FE_PROCESS_IDENTITY 的多重定义?

c++ - ffmpeg mono8/rgb24 图像到 yuv420p 到 x264 的转换

python - 如何从 csv 文件制作稀疏 pandas DataFrame