Reorder an array starting at a given position, C ++

I am new to C ++ and I am trying to do one thing that is easy in python using slice lists, but I cannot find an easy way to do this in C ++.

I need to reorder the array to start with this element, for example: int array [] = {1,2,3,4,5}; reordered array to start in element 3: {3,4,5,1,2}

so I found it, 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 greatly appreciated!

thanks

Louis

+4
source share
1 answer

Use the std::rotate method for this reordering. Put 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 item to be moved to its original 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

+5
source

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


All Articles