0

I used std::vector but it end up invalidating references upon on inserts then I moved to std::deque which works great for inserts, but now the problem is that if I delete something middle of it, it end up invalidating the rest references.

Is there any container that doesn't invalidate references on both insertion and deletion?

If not, How can I achieve what I want?

jeffbRTC
  • 1,941
  • 10
  • 29
  • 1
    I'm more curious about the underlying reason you want such a container? What is the actual underlying problem the container-change would solve? Why are you worried about invalidating iterators? Are you saving iterators somewhere (generally a bad idea)? – Some programmer dude Oct 08 '21 at 05:52
  • 7
    std::list is your choice. – 273K Oct 08 '21 at 06:00
  • 1
    Please note, that if you're storing iterators somewhere, that iterator may still become invalid, if the element the iterator points to gets removed from the list. And the iterator won't tell you. – Refugnic Eternium Oct 08 '21 at 06:20
  • std::list works as mentioned above. But you could also use map/unordered_map, and instead of storing iterators (which do become invalid), store the keys (which don't) – benroberts999 Oct 08 '21 at 07:04
  • https://stackoverflow.com/questions/6438086/iterator-invalidation-rules-for-c-containers – Sandro Oct 08 '21 at 07:46
  • `std::vector>` might be an option, the pointer won't change. (but iterator and reference to the `unique_ptr` might be invalidated). – Jarod42 Oct 08 '21 at 08:16
  • @Someprogrammerdude What are you on about? Storing iterators is a great idea (when they are not invalidated). – eerorika Oct 08 '21 at 08:50

2 Answers2

1

std::list might do what you want -- insertion does not invalidate any references or iterators on the list, and deletion just invalidates references/iterators pointing at the element deleted.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
0

Is there a C++ container that doesn't invalidate references on insertion/deletion?

All node based containers are such. They invalidate only references to the removed element on remove, and the end iterator in case of both operations.

The linked lists and the associative containers are node based.

moved to std::deque which works great for inserts, but now the problem is that if I delete something middle of it, it end up invalidating the rest references.

There's no difference for invaldation of insert and removal operations of deque. In either case, if you operate on the ends, then no references are invalidated (except end, begin, and removed element) and if you operate in the middle, then references are invalidated.

eerorika
  • 232,697
  • 12
  • 197
  • 326