chrise chrise - 1 month ago 6
C++ Question

c++ how to get address of an object in a vector from iterator

I have a vector vec that contains objects Order (not pointers to the objects)

Now I need to find a certain object in the container and manipulate it

for ( auto it = vec.begin(); it != vec.end(); ++it ) {

Order *p_o = it; // ERROR HERE
if ( p_o->id_ == id ) { p_o->size_ -= reduce_amount; }

}


error: C2440: 'initializing': cannot convert from 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Order>>>' to 'Order *'


How can I get the the address of the object the iterator hold

I tried both

it.pointer
it.reference


but that yields

C:\CPP\Simulator\Venue\venue.cpp:88: error: C2274: 'function-style cast': illegal as right side of '.' operator

Answer

Iterators model pointers, but aren't necessarily pointers themselves. So just dereference it, and if you really need to point at the object, take the address of that:

auto& my_ref_to_the_object = *iter;
auto* my_ptr_to_the_object = &my_ref_to_the_object;

Your code doesn't seem like you need a real pointer to the object at all:

for (auto it = vec.begin(); it !=  vec.end(); ++it) {
    Order& p_o = *it;
    if (p_o.id_ == id) {
        p_o.size_ -= reduce_amount;
    }
}

Or even simpler:

for (Order& p_o : vec) {
    if (p_o.id_ == id) {
        p_o.size_ -= reduce_amount;
    }
}
Comments