c++ - Iterator de-reference then "."operator versus. "->"运算符(operator)

标签 c++ listiterator

我得到了一些具有以下结构的列表/迭代器的 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/

相关文章:

列表错误上的 C++ 迭代器

c++ - 在另一个进程使用 std::fstream 写入文件时从文件中读取

c++ - 如何快速检测mysql服务器宕机状态

Java ListIterator 澄清

java - 从列表中删除字符串并在java中排序

java - 使用多线程迭代列表

c++ - Wxwidgets/Wx Perl 网格大小问题

c++ - C 与 C++ 中 void* 的转换

c# - 关于 "GUI in C# and code in C++"

java - 需要在 java 中使用迭代器的帮助