我得到了一些具有以下结构的列表/迭代器的 C++ 代码。
typedef struct{
int x;
int y;
}my_struct;
std::list<my_struct> the_list;
std::list<my_struct>::iterator the_iter = the_list.begin();
然后代码以这种方式访问 the_iter
的 x 和 y:
(*the_iter).x;
(*the_iter).y;
我想将这些更改为更具可读性的版本:
the_iter->x;
the_iter->y;
从我的 C 角度来看,这对于指针取消引用来说完全没问题。迭代器也是这样吗?我的同事有什么理由使用 (*pointer).
而不是 p->
最佳答案
考虑到一般情况,可能会出现某些迭代器类未提供 operator ->
的情况。 ,并做 (*it).x
将是唯一可能的方法。另一种可能性是 operator *
和 operator ->
有一些非标准语义并且不可互换。但是,此类无法满足任何迭代器概念,并且从技术上讲,它不是迭代器。
在你的例子中是 std::list<T>::iterator
,为此 it->x
和 (*it).x
是等价的。
关于c++ - Iterator de-reference then "."operator versus. "->"运算符(operator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809019/