-2

Suppose I have a std container that has a total of hundred elements in it. I then removed the 50th element from the container.My questions are as follows

1-If the container is a `std::vector` what iterators will become invalidated.
2-If the container is a `std::list` what iterators will become invalidated.
3-If the container is a `std::deque` what iterators will become invalidated.
4-If the container is a `std::map` what iterators will become invalidated. 

Here are the answers according to my understanding please correct me if I am wrong

1-If the 50th element is removed in a vector all the next elements will move one step up since a vector is a dynamic array and its contiguous. So iterators before 50th index would be valid and iterators greater than or equal to 50 would be invalidated after the remove

2-If the container is a list (double link list) and 50th index is removed only the iterators after or equal to the 50th index would be affected.

3-If the container is a deque I am not sure which iterators would get invalidated

4-if the container is a map I believe all the iterators would get invalidated.

(0-100) since reordering/sorting would be required. please correct me if I am wrong.

MistyD
  • 13,289
  • 28
  • 108
  • 198

1 Answers1

3

1-If the 50th element is removed in a vector all the next elements will move one step up since a vector is a dynamic array and its contiguous. So iterators before 50th index would be valid and iterators greater than or equal to 50 would be invalidated after the remove

Correct. (Source)

2-If the container is a list (double link list) and 50th index is removed only the iterators after or equal to the 50th index would be affected.

Incorrect. Only iterators pointing at the 50th index are invalidated (the list nodes are relinked, not moved) (Source)

3-If the container is a deque I am not sure which iterators would get invalidated

"All iterators and references are invalidated, unless the erased elements are at the end or the beginning of the container, in which case only the iterators and references to the erased elements are invalidated." (Source)

4-if the container is a map I believe all the iterators would get invalidated.

Incorrect. The same explanation as for std::list applies (std::map is a linked tree). (Source)

Quentin
  • 58,778
  • 7
  • 120
  • 175