为什么我无法为迭代器分配向量索引值?

Why I am unable to assign an iterator with vector index values?

示例代码

std::vector<int> testvectr;
std::vector<int>::iterator it;
testvectr.push_back(10);
it = testvectr.begin(); // method 1 - works 
it = &(testvectr[0]); //  method 2  - errors as  binary '=': no operator found which takes a right-hand operand of type '_Ty *'

为什么会抛出错误?我正在尝试分配矢量索引。所以以后我可以用 *it 来调用它。 但我不明白它背后的错误。请帮助。

std::vector<T>::iterator不一定是T *。如果您有一个指向向量元素的指针 p 并且想要获得指向该相同元素的迭代器,您可以使用以下指针算法:

auto it = v.begin() + (p - v.data());