1

I'm making a small game and I'm atempting to use vector as a container to store all entites in the world. However I need a way to frequently insert and delete entites. I'm currently using this to delete entities:

std::swap(m_entities[index], m_entities.back()); m_entities.pop_back();

But I have no way of checking if an item exists so it crashes if I accidently try to remove item. Also the index is stored in the entity so the index will be invalid for the swapped entity right? Should I use an unordered_map instead?

  • 1
    You could just use `vector::erase()`. P.S. I like your username. – SingerOfTheFall Oct 31 '16 at 06:59
  • `vector::erase` seems more sound, but look at `vector::at` for when you want to test that you are in bounds. Or just `if (index – user4581301 Oct 31 '16 at 07:19
  • vector is maybe not the right container due to numerous insertions / deletions that the game will occur. This is due to the fact that [vector](http://www.cplusplus.com/reference/vector/vector/erase/) must always ensure to have contiguous data (so that it may be accessed like a old C array). Maybe see my answer to a related question [c-storing-an-object-into-an-array-of-objects-within-the-constructor-of-that-object](http://stackoverflow.com/questions/25838551) – NGI Oct 31 '16 at 07:41
  • Your final ponder at first-glance seems a good match. An `unordered_map>` seems like it would play much nicer with this task. Whether there are other reasons that may not be a solid candidate are left to you, as we don't have much to work with. I strongly suggest you drop the raw-pointer storage and move into the modern C++ realm of smart pointers, btw. – WhozCraig Oct 31 '16 at 07:51
  • Ok thanks everyone! I was trying to use vector becasue of the efficiency but i think using unordered map will save me a lot of headache. – LASER BEAR ASSAULT UNIT Oct 31 '16 at 12:05
  • 1
    Should the last line be there. You just removed the item from the back by poping it. Why delete the value that was moved into its old loction? – Martin York Oct 31 '16 at 13:18
  • Loki Astari : Agreed, `delete m_entities.back();` then `m_entities.pop_back();` feels more correct. – cmourglia Nov 01 '16 at 10:17
  • Yea my bad, in my actual program I'm passing an entity into a function and deleting that entity. I just removed it. – LASER BEAR ASSAULT UNIT Nov 04 '16 at 06:10

1 Answers1

0

You should analyse the real usage of your container, then refer a benchmark, e.g. this one:

http://baptiste-wicht.com/posts/2012/12/cpp-benchmark-vector-list-deque.html

A more general STL complexity page is here:

https://john-ahlgren.blogspot.de/2013/10/stl-container-performance.html

Trantor
  • 768
  • 1
  • 8
  • 27