[Solved] How to put an element from an array infront of another element.?


A generic, in-place solution might be:

#include<vector>
#include<cassert>
#include<algorithm>

// random iterator, the behaviour is undefined if first == second, or
// first and second do not belong to some valid range
template<typename RIter>
void move_in_front_of( RIter first, RIter second )
{
  std::iter_swap(first,second);

  if( first < second )
    std::rotate(std::next(first),second,std::next(second));
  else
    std::rotate(std::next(second),first,std::next(first));
}

int main()
{
  auto v1 = std::vector<int>{5,7,3,6,4};
  auto v2 = std::vector<int>{3,5,7,6,4};
  auto v3 = std::vector<int>{3,5,6,7,4};
  auto v4 = std::vector<int>{3,4,5,6,7};

  move_in_front_of( v1.begin()+2, v1.begin() );//3,5
  assert( v1 == v2 );
  move_in_front_of( v1.begin()+3, v1.begin()+2 );//6,7
  assert( v1 == v3 );
  move_in_front_of( v1.begin()+4, v1.begin()+1 );//4,5
  assert( v1 == v4 );
}

solved How to put an element from an array infront of another element.?