Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ vector reverse algorithm [closed]

Tags:

c++

I am trying to make a simple program which basically reverse the sequence of the vector. In other words after the program is ran, x[0] should be equal to 5. The output which I am currently getting is 5234. The 1 goes missing somewhere. I did include the <vector> header. Thanks in advance.

int main()
{
    vector<int> x(5);
    x[0] = 1;
    x[1] = 2;
    x[2] = 3;
    x[3] = 4;
    x[4] = 5;
    for(int z = 0; z < x.size()-1; z++)
    {
        int temp = x[x.size() - (1+z)];
        x[x.size() - (1+z)] = x[z];
        x[z] = temp;
    }
    for(int s = 0; s < x.size() - 1; s++)
    {
        cout << x[s] << endl;
    }
    return 0;
}
like image 644
Stanimirovv Avatar asked May 07 '26 10:05

Stanimirovv


1 Answers

Take a step back a minute. What do you think this will do if I just put in swap (pseudo code)

for( elt1 = begin, elt2 = end-1; elt1 != end; ++elt1, --elt2 )
{
    iter_swap( elt1, elt2 );
}

This will not reverse your collection. Or rather it will, but will then reverse it back again leaving you where you started. Say your collection has 4 elements:

swap( 0, 3 )
swap( 1, 2 )
swap( 2, 1 )
swap( 3, 0 )

So your terminating condition is wrong, you should only swap halfway...

like image 104
CashCow Avatar answered May 10 '26 01:05

CashCow



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!