c++ - 为什么 std::iterator 不包含 std::prev() 作为成员函数?

标签 c++ iterator std member-functions non-member-functions

it++;                       // OK    : Widely used expression for moving iterator.

it_prev = it-1;             // ERROR : What I expected; + - operators never existed
it_prev = std::prev(it)     // OK

it_next3 = it+3;            // ERROR : also, nothing like this exists
it_next3 = std::next(it,3)  // OK

为什么 Iterator 类没有 + - 运算符作为成员函数?

或者 std::prev() 作为成员函数来执行此操作?

it_prev = it.prev()         // nothing like this

在迭代器外部定义 prev 函数是否有特殊原因?

最佳答案

如果 prev() 是一个成员函数而不是自由函数,那么它的通用性就会降低,因为它不可能使用内置类型(例如指针)作为迭代器:

int *ptr = ...
// ...
ptr.prev() // <-- Pointers don't have member functions!!

而对于非成员函数模板,例如std::prev(),它使用指针所需的只是处理以下内容的专门化:指针:

int *ptr = ...
// ...
std::prev(ptr); // <-- OK

指针还支持递增递减运算符(即++--),因此在迭代器类中定义它们并不妨碍泛型编程。同样的推理也适用于二元运算符 +-

关于c++ - 为什么 std::iterator 不包含 std::prev() 作为成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118142/

相关文章:

c++ - 在游戏中组织实体的最佳方式?

c++ - 如何在 C++ 中转储嵌套映射以进行调试?

c++ - 高效的中值计算

c++ - std::stod 忽略小数点后的非数值

C++ template double std::complex<double> 范数和积

c++ - 堆栈溢出访问大 vector

c++ - 拔下设备后,DriverKit USB 驱动程序 (dext) 进程不会终止

c++ - 预编译头问题

c# - 有没有办法在迭代期间编辑字典的值?

c++ - 我们可以在没有 'advance' 函数的情况下增加迭代器多个位置吗?