我需要实现对迭代器的引用。 我知道这看起来很奇怪。但是这个要求是需要的,因为迭代器在多个函数调用中被更改(升级),并且我需要知道最新(更新的)值。我尝试过这种植入。有什么建议 - 如何正确地做到这一点?
struct strange{
std::vector<int>::iterator& it;
strange(std::vector<int> &v): it(v.begin()){}
};
main.cpp:14:45: error: cannot bind non-const lvalue reference of type ‘std::vector::iterator&’ to an rvalue of type ‘std::vector::iterator’
14 | strange(std::vector<int> &v): it(v.begin()){}
问题是
std::vector<T>::begin
返回 by value,这意味着 v.begin()
是一个 rvalue。由于右值无法绑定到非常量左值引用,因此我们收到了上述错误。