在满足终止条件之前终止“ for”循环

时间:2019-05-31 10:18:54

标签: c++ arrays

编辑:已解决

这是一个将大小为'n'的数组向左旋转'd'的程序。 例如:d = 3的1 2 3 4 5 6 7转到4 5 6 7 1 23。我的问题是关于int main()中用于打印数组的最终循环。该循环不会将数组打印到所有'n'个成员。

我尝试为特定的“ n”打印数组,例如n = 7。在这种情况下,它可以工作。因此,我认为rotleft()函数中没有任何逻辑错误。

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int arr[],int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d,arr[n];

    cin>>n>>d;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

当在最后一个循环中用7替换'n'时,我得到了准确的结果,但是对于一般的'n',它显示的是4 5 6而不是4 5 6 7 1 2 3(请参见上面的示例)。 / p>

3 个答案:

答案 0 :(得分:4)

您正在初始化n之前创建数组,因此可能没有足够的空间容纳所有成员。

// n is used here
int n,d,arr[n];
// Initialized here
cin>>n>>d;

例如,您可以使用std::vector代替数组。使用它,您在声明变量时不必知道大小。

答案 1 :(得分:0)

C++ does not support array of dynamic size yet. The size of array needs to be known at compile time. So as suggested already, use vector instead of array if your size is dynamic.

You may achieve the same result by using already existing library function: std::rotate(). However, if you are trying to learn to implement rotate yourself then, its fine.

答案 2 :(得分:-3)

对于动态分配的数组,应在堆上使用指针和内存分配。否则,变量将从内存中获得分配的随机值。

http://www.cplusplus.com/doc/tutorial/dynamic/

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int* arr,int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d;

    cin>>n>>d;
    int* arr = new int[n];

    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }

    delete [] arr;
    return 0;
}
相关问题