C++ 迭代器与带有 length() 方法的对象

标签 c++ iterator idioms

我的问题引用了 Maya C++ API 中的示例我想知道它是 Maya 特有的还是通用的 C++ 习惯用法

在 Maya API 中,有一个名为 MSelectionList 的对象,它是表示场景中对象的容器。它还有一个配套的 MItSelectionList,它是 MSelectionList 实例的迭代器。

现在我明白迭代器的好处是它知道如何正确循环对象,但在本例中 MSelectionList 有一个 .length() 方法,以及与迭代器相同的 getter,只不过您提供了索引。

示例...

<强> MSelectionList

MSelectionList activeList;
MGlobal::activeSelectionList(activeList);

unsigned int length = activeList.length();
for (unsigned int i=0 ; i < length; i++ ) {
    MDagPath item;
    iter.getDagPath(i, item);
}

<强> MItSelectionList

MSelectionList activeList;
MGlobal::activeSelectionList(activeList);
MItSelectionList iter( activeList );

for ( ; !iter.isDone(); iter.next() ) {
    MDagPath item;
    iter.getDagPath(item);
}

与普通选择对象相比,迭代器提供的唯一功能是设置过滤器类型的能力,以便它只返回与过滤器匹配的对象。尽管您可以在第一个示例中显式执行相同的测试。

我的问题是,当迭代器和原始对象之间的功能存在重叠时,迭代器有什么好处?这只是 Maya 特定的设计决策,还是因为某些我在这里不理解的额外原因而始终创建迭代器的通用 C++ 习惯用法。

最佳答案

我对Maya不熟悉,但我相信这个问题与“迭代器与索引”之间的争论有关。

根据wikipedia article for iterators ,迭代器有以下优点:

  • Counting loops are not suitable to all data structures, in particular to data structures with no or slow random access, like lists or trees.
  • Iterators can provide a consistent way to iterate on data structures of all kinds, and therefore make the code more readable, reusable, and less sensitive to a change in the data structure.
  • An iterator can enforce additional restrictions on access, such as ensuring that elements can not be skipped or that a previously visited element can not be accessed a second time.
  • An iterator may allow the container object to be modified without invalidating the iterator. For instance, once an iterator has advanced beyond the first element it may be possible to insert additional elements into the beginning of the container with predictable results. With indexing this is problematic since the index numbers must change.

对于您的特定示例,看起来第三个项目符号最适用,因为 MItSelectionList 仅公开 next() 成员函数来强制不跳过元素(除非应用过滤器)。

关于C++ 迭代器与带有 length() 方法的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11875386/

相关文章:

c++ - 从 C++ 调用 powershell cmdlet

c++ - 在不调用析构函数的情况下结束 STL 容器的生命周期

python - 将迭代器转换为列表会更改迭代器

Java HashMap 迭代器

python - 分配给 "_ "的原因

c++ - C++ 中的非线性编程库

c++ - 无法访问同一类的私有(private)成员

javascript - JS中数字原型(prototype)的自定义迭代器

go - 将 rune 转换为int?

ColdFusion:从列表中选择第一个非空值