Moving a vector element in the opposite direction of a vector

Is there a better way (faster or with fewer code characters) than erasing an element and re-adding it 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); } 
+6
source share
3 answers

You can do this with std::rotate from the standard library. Since this does not change the size of the vector, it also does not lead to redistribution. Your function will 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()); } 
+27
source

Perhaps the quickest way would be to replace 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 should work with T

+5
source

You can avoid the extra variable.

 v.push_back(v[itemIndex]); v.erase(v.begin() + itemIndex); 

If you often delete from the middle of the vector and can rewrite your code so that it does not require random access, you can increase efficiency by using the linked list ( std::list ).

+4
source

Source: https://habr.com/ru/post/969653/


All Articles