Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Move certain elements of std::vector to a new index within the vector?

I am porting some old hand rolled array processing classes I wrote to now use the std library containers. One method I am having trouble porting is what I call "ChangeRecordOrder" for lack of a better term. I need a standard library replacement.

Its definition is:

template <class T>
void ChangeRecordOrder( std::vector<T> IN OUT &inputVector, 
                        uint newInsertIndex, 
                        std::vector<uint> IN const &indexesToMoveToNewIndex );

For example (Pseudo code):

MyVector<uint> = {0,10,20,30,40,50,60,70,80,90}
IndexesToMove = {2,4}
NewIndex = 6

After call to ChangeRecordOrder( MyVector, NewIndex, IndexesToMove ):

MyVector<uint> == {0,10,30,50,20,40,60,70,80,90}

Note that the elements at 2 and 4 (20 and 40), were moved to index 6 of the original vector (in front of 60).

Of course I would like to do this in place, and not use another temporary vector. I also dont mind the requirement that the IndexesToMove vector needs to be sorted before calling.

I couldn't find an std lib algorithm for this. The algorithm that I had before worked on the raw memory and did not use c++ move semantics.

Thank you!

like image 884
Scott Kemp Avatar asked Oct 14 '25 08:10

Scott Kemp


1 Answers

template <typename t> void move(std::vector<t>& v, size_t oldIndex, size_t newIndex)
{
    if (oldIndex > newIndex)
        std::rotate(v.rend() - oldIndex - 1, v.rend() - oldIndex, v.rend() - newIndex);
    else        
        std::rotate(v.begin() + oldIndex, v.begin() + oldIndex + 1, v.begin() + newIndex + 1);
}

test: https://coliru.stacked-crooked.com/a/5c31007000b9eeba

int main()
{
    std::vector<int> v{ 3, 4, 5, 6, 7, 8, 9  };  

    move(v, 1, 4);
    move(v, 4, 1);
    move(v, 3, 3);
}

output:

move 1 to 4:  3   [4]   5    6    7    8    9  
     result:  3    5    6    7   [4]   8    9  

move 4 to 1:  3    5    6    7   [4]   8    9  
     result:  3   [4]   5    6    7    8    9  

move 3 to 3:  3    4    5   [6]   7    8    9  
     result:  3    4    5   [6]   7    8    9  
like image 153
Elan Hickler Avatar answered Oct 16 '25 23:10

Elan Hickler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!