I'm using some classes and several utility methods that use std:: vector.
Now I need to use each frame a pop_front - push_back method on one of those classes (but they are all linked, and work together so I can't change only one).
Most of the operations are iterate over all element and push_back operations, so what I should do for the best work is: fork the repository of those classes and utilities, template everything, and use deque or list.
But this means a lot of code rewriting and a lot of testing that will make me miss the deadline.
So I need advice to write an efficient pop_front to a static-size vector (the size will not change).
I've found here a way:
template<typename T>
void pop_front(std::vector<T>& vec)
{
vec.front() = vec.back();
vec.pop_back();
vec.front() = vec.back(); // but should this work?
}
And another idea should be:
template<typename T>
void pop_front(std::vector<T>& vec, already_allocated_vector vec1)
{
vec1.clear();
copy(vec.begin(), vec.end()-1, vec1.begin());
copy(vec1.begin(), vec1.end(), vec.begin());
}
What is the faster of these two solutions? Any other solutions?
pop_back_and_overwrite_front_with_penultimate
, and the second one should be namedinvoke_undefined_behavior_and_pop_back
. (Writing tovec1.begin()
is undefined becausevec1
is empty; you'd need to writevec1.resize(vec.size() - 1)
instead ofvec1.clear()
.) When I'm dealing with vector operations, I sometimes draw a picture. Maybe that would help you, too. – Rob Kennedy Feb 25 '12 at 18:25std::deque
? is as good asstd::vector
, but canpop_front()
– Sebastian Mach Feb 27 '12 at 11:08std::vector
,std::deque
is not continuous memory. – JustWe Feb 11 '20 at 6:42