我正在为我的科学软件编写一个3D网格,我需要遍历网格的节点来获取它们的坐标.而不是将每个节点对象保存在容器中,我宁愿只是在迭代时动态计算坐标.问题是stl :: iterator需要返回对值的引用operator*()或者指针的引用operator->().
下面的一些代码:
class spGridIterator {
public:
typedef forward_iterator_tag iterator_category;
typedef spVector3D value_type;
typedef int difference_type;
typedef spVector3D* pointer;
typedef spVector3D& reference;
spGridIterator(spGrid* gr, int index);
spGridIterator& operator++();
spGridIterator& operator++(int);
reference operator*() const;
pointer operator->() const;
private:
spGrid* m_grid;
int m_idx;
};
Run Code Online (Sandbox Code Playgroud)
spGridIterator::reference spGridIterator::operator*() const {
// return m_grid->GetPoint(m_idx);
}
spGridIterator::pointer spGridIterator::operator->() const {
// return m_grid->GetPoint(m_idx);
}
Run Code Online (Sandbox Code Playgroud)
此方法通过提供的索引查询节点坐标
spVector3D spGrid::GetPoint(int idx) const {
// spVector3D vec = ... calculate the coordinates here ...
return vec;
}
Run Code Online (Sandbox Code Playgroud)
有什么输入吗?
提前谢谢,伊利亚
您可以使用成员变量来保存当前指向的网格点:
class spGridIterator {
public:
typedef forward_iterator_tag iterator_category;
typedef spVector3D value_type;
typedef int difference_type;
typedef spVector3D* pointer;
typedef const spVector3D* const_pointer;
typedef const spVector3D& const_reference;
typedef spVector3D& reference;
spGridIterator(spGrid* gr, int index);
spGridIterator& operator++();
spGridIterator& operator++(int);
reference operator*();
const_reference operator*() const;
pointer operator->();
const_pointer operator->() const;
private:
spGrid* m_grid;
int m_idx;
mutable spVector3D CurrentPoint;
};
Run Code Online (Sandbox Code Playgroud)
然后解除引用运算符可能如下所示:
spGridIterator::const_reference spGridIterator::operator*() const {
CurrentPoint = m_grid->GetPoint(m_idx);
return CurrentPoint;
}
Run Code Online (Sandbox Code Playgroud)
感谢@greg指出CurrentPoint需要mutable为此工作.这将是一个惰性实现(仅在迭代器实际解除引用时检索点).一个急切的实现将更新CurrentPoint迭代器的mutator方法中的成员(operator++本例中的变体),这使得mutable多余.
| 归档时间: |
|
| 查看次数: |
2091 次 |
| 最近记录: |