在线编译器中的细分故障

发布于 2025-01-24 19:15:38 字数 790 浏览 3 评论 0原文

下面的代码在GDB和VS代码中正常工作,但其他在线编译器不断投掷“分段故障”。有人可以帮我吗?我试图解决的每个问题,我都会遇到此错误。

例如: 给出了一系列整数。在数组中查找反转计数。

反转计数:对于数组,反转计数指示数组与分类的距离(或关闭)。如果数组已经排序,则反转计数为0。如果以相反顺序对数组进行排序,则反转计数为最大值。

形式上,如果a [i]> a [j]和i< j。

代码:

long long int inversionCount(long long arr[], long long N) {
    vector<long long> v; 
    long long int count = 0;
    for (int i = 0; i < N; i++) v[i]= arr[i];

    auto min = min_element(arr, arr+ N);
    auto max = max_element(arr, arr+ N);
    swap(v[0], *min);
    v.erase(max);
    v.push_back(*max);

    for (int i = 0; i < N; i++) {
        if(v[i] > v[i+1]) {
            swap(v[i],v[i+1]);
            count++;
        }
        return count; 
    }
}

The code below works fine in gdb and VS code but other online compilers keep throwing "segmentation fault". Can anyone please help me with this? Every question I try to solve I keep getting this error.

For example:
Given an array of integers. Find the Inversion Count in the array.

Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If the array is already sorted then the inversion count is 0. If an array is sorted in the reverse order then the inversion count is the maximum.

Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.

Code:

long long int inversionCount(long long arr[], long long N) {
    vector<long long> v; 
    long long int count = 0;
    for (int i = 0; i < N; i++) v[i]= arr[i];

    auto min = min_element(arr, arr+ N);
    auto max = max_element(arr, arr+ N);
    swap(v[0], *min);
    v.erase(max);
    v.push_back(*max);

    for (int i = 0; i < N; i++) {
        if(v[i] > v[i+1]) {
            swap(v[i],v[i+1]);
            count++;
        }
        return count; 
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与风相奔跑 2025-01-31 19:15:38

您在这里有很多问题。首先,您尝试使用v中的元素,而无需为它们分配空间(即,即使其大小仍然是v的元素, 。

std::vector<long long> v { arr, arr+N};

         v.erase(max);

元素 先前指向的任何点,以及集合的结尾。

         v.push_back(*max);

迭代器或引用元素max

You have a number of problems here. For one, you try to use elements in v without ever allocating space for them (i.e., you're using subscripts to refer to elements of v even though its size is still zero elements. I'd usually use the constructor that takes two iterators to copy an existing collection (and pointers can be iterators too).

std::vector<long long> v { arr, arr+N};

Assuming you fix that, this:

         v.erase(max);

... invalidates max and every other iterator or reference to any point between the element max previously pointed to, and the end of the collection. Which means that this:

         v.push_back(*max);

...is attempting to dereference an invalid iterator, which produces undefined behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文