【问题标题】:Code doesn't seem to work for larger inputs, but works fine for smaller inputs [duplicate]代码似乎不适用于较大的输入,但适用于较小的输入[重复]
【发布时间】:2017-12-02 23:37:02
【问题描述】:

在解决 this question 时,我的代码似乎不适用于 100000 等较大的输入,但似乎适用于较小的输入。

代码如下:

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
long long int n, h;
cin>>n;
long long int count=0;
long long int i,j;
long long int arr[n];
for(i=0;i<n;i++)
{
    cin>>arr[i];
    //cout<<arr[i]<<" ";
}
h = arr[0];
for(i=0;i<n;i++)
{
    if (arr[i]>=h)
    {
        h=arr[i];
        for(j=i;j<n;j++)
        { if (arr[j]<h)
                count++;
        }       


    }
}
cout<<(n-count);
//cout<<h;    
return 0;
}

谁能帮帮我?

【问题讨论】:

  • 这实际上不是 C++,因为您忽略了可以避免这些问题的出色标准库容器,而是使用 VLA 的非标准扩展。
  • 明白了,抱歉我是初学者,所以没有太多经验。感谢您的帮助。

标签: c++ arrays c++11


【解决方案1】:

首先,VLA (arr[n]) 在 C++ 中是非标准的。其次,在支持它们的地方(例如,作为 g++ 中的语言扩展),它们通常存储在堆栈中,堆栈大小有限,因此您很可能会遇到...堆栈溢出。解决方案:使用适当的 C++ 容器(例如 std::vector)而不是 VLA,例如改变:

long long int arr[n];

到:

std::vector<long long int> arr(n);

(别忘了#include &lt;vector&gt;)。

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2015-12-02
    • 1970-01-01
    相关资源
    最近更新 更多