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/