Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving a vector element to the back of the vector

Tags:

Is there any better way (either faster or with fewer symbols of code) than erasing the element and re-adding it to the back?

template <typename T> void moveItemToBack(std::vector<T>& v, size_t itemIndex) {    T tmp(v[itemIndex]);    v.erase(v.begin() + itemIndex);    v.push_back(tmp); } 
like image 946
Violet Giraffe Avatar asked May 21 '14 16:05

Violet Giraffe


People also ask

How do you move a vector element?

You can't move elements from one vector to another the way you are thinking about; you will always have to erase the element positions from the first vector. If you want to change all the elements from the first vector into the second and vice versa you can use swap.

How do you push elements in front of a vector?

push_front() function is used to push elements into a list from the front. The new value is inserted into the list at the beginning, before the current first element and the container size is increased by 1.


2 Answers

You can do this with std::rotate from the standard library. Since this doesn't change the vector size it also won't trigger a reallocation. Your function would look something like this:

template <typename T> void moveItemToBack(std::vector<T>& v, size_t itemIndex) {     auto it = v.begin() + itemIndex;     std::rotate(it, it + 1, v.end()); } 
like image 142
Blastfurnace Avatar answered Sep 30 '22 17:09

Blastfurnace


Possibly the fastest way, would be to swap it with the last element

template <typename T> void moveItemToBack(std::vector<T>& v, size_t itemIndex) {    std::swap(v[itemIndex], v.back()); // or swap with *(v.end()-1) } 

one operation! Ofcourse std::swap has to work with T

like image 24
Nikos Athanasiou Avatar answered Sep 30 '22 17:09

Nikos Athanasiou