user1822451
user1822451

Reputation: 111

reorder array starting at given position, c++

I'm new to C++ and I'm trying to do one thing that is easy in python using slice lists, but I can't find a easy way to do that in c++.

I need to reorder a array to start at a given element like: int array[] = {1,2,3,4,5}; reordered array to start at element 3: {3,4,5,1,2}

this is the way I found to do that, but it seems to be a bit overkill:

void Graph::reorder(int x, MIntArray &currentArray) 
{
    MIntArray reorderedIndices;
    int index;
    for (unsigned int i=0; i<currentArray.length();i++){if(currentArray[i]==x){index=i;}} // get the index
    for (unsigned int i=index; i<currentArray.length();i++){reorderedIndices.append(currentArray[i]);} // zero to index
    for (unsigned int i=0; i<index;i++){reorderedIndices.append(currentArray[i]);} // index to last
    for (unsigned int i=0; i<currentArray.length();i++){currentArray.set(reorderedIndices[i],i);} // transfer
}

any help would be much appreciated!!

thanks

luiz

Upvotes: 4

Views: 322

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Use std::rotate method to do this reordering. Supply the beginning of the array as the first parameter, the end of the array (i.e. array+length) as the last parameter, and the "midpoint" as the second parameter. Midpoint defines the index of the element to be moved to the initial position.

int x[] = {1,2,3,4,5};
rotate(x, x+2, x+5);
for (int i = 0 ; i != 5 ; i++)
    cout << x[i] << " ";
cout << endl;

This prints 3 4 5 1 2

Upvotes: 6

Related Questions