C++ 所以我必须将一个数组旋转一个位置,但不需要分配数组以外的额外空间。这是正确的解决方案吗?
这是我的解决办法。对吗?忽略bits/stdc++.h等。我只想知道它是否只使用分配给向量的空间C++ 所以我必须将一个数组旋转一个位置,但不需要分配数组以外的额外空间。这是正确的解决方案吗?,c++,arrays,algorithm,for-loop,rotation,C++,Arrays,Algorithm,For Loop,Rotation,这是我的解决办法。对吗?忽略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++) {
#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] << "; ";
}
}
#包括
使用名称空间std;
int main(){
int n;
cout>n;
int x[n];
对于(int i=0;i cout对于这样的可变长度数组
int n;
cout << "Size of array?\n";
cin >> n;
int x[n];
应该这样写
for (int i = 1; i<n; i++) {
swap(x[i-1],x[i]);
}
这是一个演示程序,其中使用了标准算法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;
}
如果这是工作的,编译使用CODERVIEW,而不是StAccExcel。首先,你的“数组”实际上是无效的,因为C++没有真正的使用。使用<代码> STD::向量< /代码>。也不使用,甚至不为简单的例子。VLA和报头都是真正的坏习惯,通常通过所谓的“竞争”暴露出来。网站。这些网站不是用来学习任何东西的,除非你想学习的都是坏习惯(坏习惯会让你失业)。也许是OT,但intx[n];
是一个可变长度数组。这就是它们的调用方式。请参见此处:。如果您希望数组的大小仅在运行时确定,但在构造后固定,简单的方法是使用std::vector
而不是在构造后添加或删除元素。世界需要更多的std::rotate。
#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;
}
1 2 3 4 5
2 3 4 5 1
#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;
}
1 2 3 4 5
2 3 4 5 1