Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the most efficient way to remove the first element from a large vector?

Tags:

c++

vector

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...

like image 259
sushi7777 Avatar asked Oct 30 '22 09:10

sushi7777


1 Answers

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.

like image 154
paddy Avatar answered Nov 02 '22 23:11

paddy