简体   繁体   中英

So I have to rotate an array by one position but withou allocating extra space other than the array. Is this a correct solution?

Here is my solution. Is it correct? Ignore bits/stdc++.h etc. I just want to know if it only uses the space allocated for the vector.

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    cout << "Size of array?\n";
    cin >> n;
    int x[n];
    for (int i = 0; i < n; i++) {
        cout << "Input x[" << i << "]:\n";
        cin >> x[i];
    }
    for (int i = 0; i < n; i++) {
        cout << x[i] << "; ";
    }
    for (int i = 1; i<n; i++) {
        swap(x[0],x[i]);
    }
    for (int i = 0; i < n; i++) {
        cout << x[i] << "; ";
    }
}

For starters variable length arrays like this

int n;
cout << "Size of array?\n";
cin >> n;
int x[n];

is not a standard C++ feature. Instead you should use the standard container std::vector<int> .

To rotate an array or an object of the type std::vector<int> you can use the standard algorithm std::rotate .

As for your code then if you want to rotate the array left then this loop

for (int i = 1; i<n; i++) {
        swap(x[0],x[i]);
}

should be written like

for (int i = 1; i<n; i++) {
        swap(x[i-1],x[i]);
}

Otherwise your loop rotates an array right.

Here is a demonstrative program.

#include <iostream>
#include <utility>
#include <vector>

int main() 
{
    std::vector<int> v = { 1, 2, 3, 4, 5 };

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';
    
    for ( size_t i = 1; i < v.size(); i++ )
    {
        std::swap( v[i-1], v[i] );
    }
    
    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';
    
    
    return 0;
}

The program output is

1 2 3 4 5 
2 3 4 5 1 

Here is a demonstrative program where there is used the standard algorithm std::rotate .

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main() 
{
    std::vector<int> v = { 1, 2, 3, 4, 5 };

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';
    
    std::rotate( std::begin( v ), std::next( std::begin( v ) ), std::end( v ) );
    
    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';
    
    
    return 0;
}

The program output is the same as shown above

1 2 3 4 5 
2 3 4 5 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM