Home > Blockchain >  Swapping elements efficiently in C vector
Swapping elements efficiently in C vector

Time:10-22

Basically, I have a vector vect. I want to move part of vect from the end, to the start, efficiently. Example:

vect before = {1,2,3,4,5,6,7}

Moving the last two elements from end to start:

vect after = {6,7,1,2,3,4,5}

Now, I have the following function:

template <class ElementType>
void endToStart(std::vector<ElementType>& vect, size_t startPos)
{
   std::vector<ElementType> temp;

   temp.reserve(vect.size());

   for (auto i = startPos; i < vect.size();   i)
   {
      temp.push_back(vect[i]);
   }
   for (auto i = 0; i < startPos;   i)
   {
      temp.push_back(vect[i]);
   }

   vect.swap(temp);
}

Is there a more efficient way of doing this?

CodePudding user response:

It looks like you need std::rotate:

#include <algorithm> // std::rotate
#include <iostream>

int main() {
    
    std::vector<int> vect = {1,2,3,4,5,6,7};

    std::rotate(vect.begin(), vect.begin()   5, vect.end());
    //                        ^^^^^^^^^^^^^^^^
    //                     the new first position                              
    
    for(auto v : vect) std::cout << v << ' ';
}

Demo

  •  Tags:  
  • c
  • Related