Reputation: 189
Say I have a vector with 100000 elements, and I wish to iterate through the vector, one by one, whilst copying the element into a map of some sort, but during each iteration, deleting the element from the vector - what is the most efficient way to do this?
Whilst iterating through the vector, I had done something like "it = vec.erase(it)" but it takes absolutely ages to complete. Is there not a quicker way? And as a side note, ordering is very important...
Upvotes: 5
Views: 2010
Reputation: 62563
Since the order of the elements in the vector can not be important - you are putting them in the map anyways - the easy solution is to swap the first element with the last, and than remove the last element. That is going to be much faster.
Upvotes: 0
Reputation: 20726
If you need to use a vector
, then given your requirements, you should use a vector
of pointers to dynamically-allocated instances of the objects instead of a vector
of objects themselves.
Upvotes: -3
Reputation: 63471
There isn't one. You are using the vector as a queue. This goes against its design.
You have a few choices. The following come immediately to mind:
Don't erase one item at a time. Do them in batches.
Use the vector as a ring buffer and just advance an index, but never remove elements.
Use a more appropriate container such as std::deque
.
Upvotes: 5