c++迭代器混乱
我有一个 vector
>
我有一个迭代器 vector
>::const_iterator x
当我尝试像这样访问 customClass 的成员时:
x[0]->somefunc()
,我收到非指针类型的错误/未找到。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我有一个 vector
>
我有一个迭代器 vector
>::const_iterator x
当我尝试像这样访问 customClass 的成员时:
x[0]->somefunc()
,我收到非指针类型的错误/未找到。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
这是一个完整的工作片段。为了回答您的问题,带有注释 [1] 的行显示了如何取消引用 const_iterator,而注释 [2] 显示了如何使用运算符 [] 取消引用。
Here's a complete working snippet. To answer your question, the line with the comment [1] shows how to dereference the const_iterator, while comment [2] shows how to dereference using the operator [].
迭代器取消引用列表。如果您想访问该列表中的对象,则必须使用列表方法来执行此操作。但是,由于 stl 列表不会重载索引运算符,因此这不是一个有效的选项。
这将允许您对列表中的第一个元素调用 somefunc:
另一方面,如果您想要列表的迭代器,您可以执行以下操作:
The iterator dereferences to a list. If you want to access an object in that list, then you will have to use the list methods to do so. However, since stl lists don't overload the index operator, that won't be a valid option.
This will let you call somefunc on the first element in the list:
On the other hand, if you want an iterator for your list, you can do something like this:
迭代器类不提供operator[],因此你不能这样使用它。您应该将其用作 x->somefunc()
iterator class does not provide operator[] hence you can not use it like that . You should use it as x->somefunc()
x 是一个迭代器,它的作用就像一个指针——它指向一个列表。所以你只能使用 std::list 成员的函数。
x is an iterator, which acts like a pointer - it points to a list. So you can only use functions which are members of std::list.
const 迭代器将取消引用
list
对象,而不是指向该列表的指针。您必须访问该类列表中的索引...忽略错误检查:
The const iterator will dereference to a
list<customClass>
object not a pointer to that list. You'd have to access the index in that list for the class...Ignoring error checking:
如果你想直接访问列表和向量类已经实现了 [] 运算符,那么只需直接访问它:vectorObj[x].someFunc();
迭代器用于遍历列表(如名称所示迭代它),请使用它。
if you want direct access the list and vector class already implement the [] operator, so just access it directly: vectorObj[x].someFunc();
iterator are for going through the list (to iterate it like the name suggests), use it for that.