[英]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.
忽略 bits/stdc++.h 等。我只想知道它是否只使用分配给向量的空间。
#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对于初学者可变长度 arrays 像这样
int n;
cout << "Size of array?\n";
cin >> n;
int x[n];
is not a standard C++ feature.不是标准的 C++ 功能。 Instead you should use the standard container
std::vector<int>
.相反,您应该使用标准容器
std::vector<int>
。
To rotate an array or an object of the type std::vector<int>
you can use the standard algorithm std::rotate
.要旋转
std::vector<int>
类型的数组或 object,您可以使用标准算法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程序 output 是
1 2 3 4 5
2 3 4 5 1
Here is a demonstrative program where there is used the standard algorithm std::rotate
.这是一个演示程序,其中使用了标准算法
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程序output同上图
1 2 3 4 5
2 3 4 5 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.