【问题标题】:Strange const_iterator behavior奇怪的 const_iterator 行为
【发布时间】:2012-02-08 21:00:31
【问题描述】:

我正在做一个 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_iterator,它们就可以工作。

【问题讨论】:

  • 你怎么知道它们不是被创造出来的?很可能编译器优化了它们,因为它们没有被使用。
  • 我知道,因为代码继续运行并给我错误,它说 const_iterator operator++() 正在尝试读取未分配的内存区域,因为它还没有被分配任何 begin() 和结束()
  • 我没有看到您发布的代码有任何明显错误:您能给我们展示一个显示问题的最小、完全可编译的程序吗?
  • 我已恢复您的编辑,因为它改变了问题,以至于所有现有的 cmets 和答案都变得毫无意义。
  • 好的,那我开个新问题。

标签: c++ matrix sparse-matrix const-iterator


【解决方案1】:

正如您所说,“mata [sic] 以前创建为 SparseMatrix&lt;double&gt;”,但您显示的 begin 和 end 标记为 const。对于要调用的const 成员函数,对象meta 必须是const,否则将调用非const 版本的begin 和end。

【讨论】:

  • 如果我想在非常量对象上调用它应该怎么做?我需要一个具有只读权限的 const 迭代器和一个具有写权限的普通迭代器。
  • @Vektor88 通常人们有非const 成员函数返回一个iterator 而const 版本返回一个const_iterator。你也可以有一个非const 函数cbegin,如果你也想返回一个const_iterator。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2015-07-20
  • 2010-10-03
  • 2021-07-12
  • 2013-10-04
  • 2019-01-23
相关资源
最近更新 更多