【发布时间】:2011-05-02 07:33:16
【问题描述】:
我正在为我的科学软件编写一个 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;
};
spGridIterator::reference spGridIterator::operator*() const {
// return m_grid->GetPoint(m_idx);
}
spGridIterator::pointer spGridIterator::operator->() const {
// return m_grid->GetPoint(m_idx);
}
该方法通过提供的索引查询节点坐标
spVector3D spGrid::GetPoint(int idx) const {
// spVector3D vec = ... calculate the coordinates here ...
return vec;
}
对此有何意见?
提前致谢, 伊利亚
【问题讨论】:
-
"问题在于 stl::iterator 需要返回对值的引用作为 operator*() 的结果,或者 operator->() 的指针" 为什么这是个问题?为了什么?
-
我不确定我是否真正理解您想要实现的目标。也许您可以包含一个客户端代码示例,以了解您如何尝试使用此集合。
-
“为什么会有问题?为什么?”因为这种方式我不得不保留一个实际变量来指向(或引用)。
-
我需要迭代器来取消对临时变量的引用,因为节点坐标应该是动态计算的,而不是存储在某个地方。