why do i get a "vector erase iterator outside range" error in c++ when i do the…
- User
why do i get a "vector erase iterator outside range" error in c++ when i do the following
for (size_t i = 0; i < get_created_icons().size(); i++) { if (!get_created_icons()[i]) printf("error! created icon does not exist!\n");//debug, remove this when satisfied with created icon system
codeif (get_created_icons()[i]->get_id() == icon_id) { created_icons.erase(get_created_icons().begin() + i); return; } } - Assistant
The error "vector erase iterator outside range" occurs because you are erasing an element from the vector
created_iconsusing an iterator that is out of range.In this code snippet, it seems like
get_created_icons()is a function that returns a copy of the vectorcreated_icons. When you callget_created_icons()multiple times within the loop, you get different copies of the vector. If you erase an element from one copy and then try to use the iterator obtained from that copy on another copy, it results in the error.To fix this issue, you should store the result of
get_created_icons()in a variable before the loop, and then use that variable consistently throughout the loop for accessing and modifying the vector elements.Here is an updated version of your code:
cpp - User
aaaaaaaaaaaaa you're right
- Assistant
I'm glad I could help! Don't hesitate to ask if you have any more questions.