迭代器随后解除引用“。”。运算符对。 “ - >”运算符 [英] Iterator de-reference then "." operator versus. "->" operator
问题描述
我已经得到一些c ++代码,它们具有以下struct的列表/迭代器。
typedef struct {
int x;
int y;
} my_struct;
std :: list< my_struct>列表;
std :: list< my_struct> :: iterator the_iter = the_list.begin();
然后代码访问 the_iter
这样:
(* the_iter).x;
(* the_iter).y;
我想将这些更改为更易读的版本:
the_iter-> x;
the_iter-> y;
从我的角度来看,这对于指针解引用是完全正确的。迭代器也是这样吗?是否有任何理由为什么我的同事会使用(*指针)。
而不是 p>
operator - > $ c $ c>,并且执行(* it).x
将是唯一可能的方法。另一种可能性是 operator *
和 operator - >
有一些非标准语义,不能互换。但是,这个类不能满足任何迭代器的概念,而且技术上不会是迭代器。
在你的情况下,它是 std: :list< T> :: iterator
,其中 it-> x
和 / code>是等效的。
Let me preface this by saying I usually develop in c and am only familiar with c++.
I've been given some c++ code that has a list/iterator of the following struct.
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 code then accesses x and y of the_iter
this way:
(*the_iter).x;
(*the_iter).y;
I want to change these to the more readable version:
the_iter->x;
the_iter->y;
From my c perspective, this is totally fine for pointer dereferencing. Is this also the case for iterators? Is there any reason why my colleague would use (*pointer).
instead of p->
解决方案 Considering the general case, it could happen that some iterator class did not provide operator ->
, and doing (*it).x
would be the only possible way. Another possibility is that operator *
and operator ->
have some non-standard semantics and are not interchangeble. However, this class would fail to satisfy any iterator concept, and, technically, would not be an iterator.
In your case it is std::list<T>::iterator
, for which it->x
and (*it).x
are equivalent.
这篇关于迭代器随后解除引用“。”。运算符对。 “ - >”运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!