Reputation: 3
Sample code
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 *'
Why its throwing error? I am trying to assign a vector index. So later I can call it by *it. But I didn't understand the error behind it. Pls help.
Upvotes: 0
Views: 38
Reputation: 63154
std::vector<T>::iterator
is not necessarily T *
. If you have a pointer p
to an element of a vector and want to get an iterator to that same element, you can use the following pointer arithmetic:
auto it = v.begin() + (p - v.data());
Upvotes: 1