在学习 C++ 中的迭代器时,我尝试了以下方法:
#include <vector>
int main() {
std::vector<int> a;
a.end()=a.begin();
//Why is this even allowed by the compiler?
}
我错过了什么?
最佳答案
如果例如函数结束将返回一个指针,那将是不可能的。
例如这段代码不会被编译
int a[] = { 1, 2, 3 };
std::end( a ) = std::begin( a );
GCC 问题
error: lvalue required as left operand of assignment
std::end( a ) = std::begin( a );
^
但是,当使用类类型的对象时,它们可以调用重载的复制(或移动)赋值运算符。
那么问题来了,为什么函数不返回常量迭代器对象。我认为可以应用 operator++
。例如
auto it = ++c.begin();
对于作为指针的直接访问迭代器,您可以简单地编写
auto it = begin( a ) + 1;
关于c++ - 为什么编译器允许在 C++ 中使用 vector.begin()=vector.end()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25958588/