Hi, I am a rookie when it comes to C++ and would appreciate your insight, so I can go up on the learning curve.
I am trying to write a function that reorders the elements of an array where the odd numbers are to the left, in their initial relative order, whereas the even numbers are to the right, and in reverse order.
For example {13, 6, 87, 12, 45, 14} will output {13, 87, 45, 14, 12, 6}
I couldn't come up with straightforward logic, so I wonder if there is a way to put the odd values in a new temporary array, which can later be passed onto the main (and similarly a separate temp array for the even numbers).
I would recommend to use std::vector instead of arrays.
You could use std::copy_if to copy the odd numbers into a new vector, the same for even numbers. Finally you add these 2 vectors together.
@salem c, good question - yes, that I can tell - using %2 and determining if it is == 0 or not
@ coder777, your suggestion seems very straightforward, but I am taking a class, and the requirement is to follow the book (and copy_if hasn't been taught yet) ... which opens a lot of other questions as to whether I should be taking this class to start with
#include <iostream>
#include <vector>
usingnamespace std;
int main()
{
vector<int> A = { 13, 6, 87, 12, 45, 14 };
vector<int> B( A.size() );
int odd = 0, even = A.size() - 1;
for ( int e : A )
{
if ( e % 2 ) B[odd++ ] = e;
else B[even--] = e;
}
for ( int e : B ) cout << e << " ";
}
whether I should be taking this class to start with
Well it depends what you want. If you want to learn C++ the hard way then go ahead.
If you want to learn modern C++ - which is much easier - then look for sth. else.