简体   繁体   English

为什么这个 C++ 程序会崩溃?

[英]Why is this C++ program crashing?

I don't have a clue why this program is crashing?我不知道为什么这个程序会崩溃? Here is my code that I'm working on.这是我正在处理的代码。 Thanks.谢谢。

Also someone said that int a[n];还有人说int a[n]; is VLA, which is not legal in C++... But I have used the same syntax for my other programs and it has worked.是 VLA,这在 C++ 中是不合法的……但是我在其他程序中使用了相同的语法并且它有效。

#include<iostream>
#include<climits>

using namespace std;

int main()
{
    int n;
    cin>>n;

    int a[n];
    for(int i= 0; i<n; i++)
    {
        cin>>a[i];
    }

    const int N = 1e6 + 2;
    int idx[N];
    for(int i = 0; i<N; i++)
    {
        idx[i] = -1;
    }
    int minidx = INT_MAX;
 
    for(int i = 0; i<n; i++)
    {
        if (idx[a[i]] != -1)
        {
            minidx = min(minidx, idx[a[i]]);
        }
        else
        {
            idx[a[i]] = i;
        }
        
    }
    if (minidx == INT_MAX)
    {
        cout<<"-1"<<endl;
    }
    else
    {
        cout<<minidx + 1<<endl;
    }
    
    return 0;
}

Try to dynamic allocate the memory.尝试动态分配内存。 You have 1M of elements in that array, which might be a little to much for the stack.该数组中有 1M 个元素,这对于堆栈来说可能有点多。

As @Neko said, your stack can not hold the array.正如@Neko 所说,您的堆栈无法容纳数组。

In addition, I like to say that since you tagged this question 'C++' perhaps you go with std container such as std::vector另外,我想说,既然你把这个问题标记为“C++”,也许你会选择std::vector类的 std 容器

#include<iostream>
#include<climits>

int main()
{
    int n;
    std::cin>>n;

    std::vector<int> a(n);
    for(int i= 0; i<n; i++)
    {
        std::cin>>a[i];
    }

    const int N = 1e6 + 2;
    
    std::vector<int> idx(M);
    std::fill(idx.begin(), idx.end(), -1);
    
    int minidx = INT_MAX;
 
    for(int i = 0; i<n; i++)
    {
        if (idx[a[i]] != -1)
        {
            minidx = min(minidx, idx[a[i]]);
        }
        else
        {
            idx[a[i]] = i;
        }
        
    }
    if (minidx == INT_MAX)
    {
        std::cout<<"-1"<<endl;
    }
    else
    {
        std::cout<<minidx + 1<<endl;
    }
    
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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