在递归函数中使用迭代器进行段错误 [英] Seg fault with iterators in a recursive function

查看:212
本文介绍了在递归函数中使用迭代器进行段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用递归函数对向量中的整数进行排序。我的程序运行,编译和排序数据,但事实上它给了我一个seg错误。我认为这是因为for循环使用了向量中已经更改的地址,导致它永远不会离开循环。

I'm trying to sort integers in a vector using a recursive function. My program runs, compiles, and sorts the data, but after the fact it gives me a seg fault. I think its because of the for loop using the addresses in the vector that have been changed causing it to never leave the loop.

void Plays::SortRelevance(vector<Plays> list){

cout << "in the loop" << endl;

for(vector<Plays>::iterator i=list.begin(); i != list.end(); ++i){
    cout << i->relevance << endl;
}

for(vector<Plays>::iterator i=list.begin(); i != list.end(); ++i){
    if(i->relevance < (i+1)->relevance){
        cout << "IN THE THINGY WAT" << endl;
        Plays temp(*i);
        list.erase (i);
        list.push_back (temp);
        SortRelevance(list);
        cout << "left recursive" << endl;

    }

    cout << "stuck?" << endl;
}
cout << "left the loop" << endl;
for(vector<Plays>::iterator i=list.begin(); i != list.end(); ++i){
    cout << i->relevance << endl;
}

}

我的输出结束如下,排序但最后给出一个seg错误:

The end of my output is as follows, sorted but giving a seg fault at the end:

    IN THE THINGY WAT
in the loop
-62
-62
-62
-69
-71
-72
-80
-81
-87
-89
-94
-100
-104
-107
-107
-112
-137
-142
-145
-150
-151
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
stuck?
Segmentation fault

提前感谢任何可以为我解释这一点的人。

Thanks in advance to anyone who can shed some light on this for me.

编辑:我没有解决问题,因为我找到了更好,更优雅的方法。我创建了一个类,重载了运算符,然后使用sort()函数对我需要做的事情进行排序。

I haven't so much as fixed the problem as I have found a better and more elegant way to do it. I created a class, overloaded the operators and then used the sort() function to sort what I needed to do.

推荐答案

你不能对无效的迭代器进行操作,并且 erase(it)使 无效。典型的擦除循环如下所示:

You mustn't operate on invalid iterators, and erase(it) invalidates it. The typical erase loop looks like this:

for (auto it = v.cbegin(); it != v.cend() /* not hoisted */; /* no increment */)
{
    if (delete_condition)
    {
        it = v.erase(it);    // or "v.erase(it++);"
    }
    else
    {
        ++it;
    }
}

(标准中有一些清理) C ++ 11中的库使所有容器擦除函数返回下一个迭代器,但是没有使用,并且 it ++ 的版本可能正常工作在更多平台上。)

(There has been some clean-up in the standard library in C++11 to make all container-erase functions return the next iterator, but that didn't use to be the case, and the version with it++ may be work on more platforms.)

这篇关于在递归函数中使用迭代器进行段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆