std :: list iterator.erase()导致无效指针

时间:2014-01-20 02:57:00

标签: c++ c++11

嗨我遇到std::list的问题,我在调用擦除函数时遇到free():无效指针错误,然后迭代到该元素。我希望它会跳过那个元素,因为它被删除了......我的第一个假设是你可能需要一个新的迭代器,因为前一个是陈旧的。所以我的解决方案是将我的迭代器设置为list.begin()然后推进它。但这仍然会导致错误。

我要做的是将列表中的元素设置为前面n个空格的元素。然后删除前面n个空格的元素。

#include "roulette.h"
#include <iostream>

uint roulette(uint people, uint step)
{
    std::list<uint>::iterator iterator;
    uint position = 0;

    for(uint i = people; i > 0; i--)
        gl_myList.push_front(i);

    iterator = gl_myList.begin();
    while(people > 1)
    {
        for(uint i = 0; i < step - 1; i++)
        {
            position++;
            iterator++;
            if(iterator == gl_myList.end())
            {
                iterator = gl_myList.begin();
                position = 0;
            }
        }
        *iterator = kill(iterator, step);

        /*
         * This was my attempt to fix it
        iterator = gl_myList.begin();
        advance(iterator, position);
        */

        people--;
    }

    return *iterator;
}

#include "roulette.h"
#include <iostream>
uint kill(std::list<uint>::iterator iterator, uint step)
{
    uint value;
    for(uint i = 0; i < step; i++)
    {
        iterator++;
        if(iterator == gl_myList.end())
            iterator = gl_myList.begin();
    }
    value = *iterator;
    gl_myList.erase(iterator);
    return value;
}

2 个答案:

答案 0 :(得分:2)

当您的kill函数返回时,您尝试将返回值分配给*iterator - 但您在kill中使迭代器无效!

答案 1 :(得分:2)

也许是这样的:

std::list<uint>::iterator advanceList(std::list<uint>::iterator start, int step) {
    for(uint i = 0; i < step; i++) {
        start++;
        if(start == gl_myList.end())
            start = gl_myList.begin();
    }
    return start;
}

在您的主要代码中:

while(people > 1) {
    iterator = advanceList(iterator, step);
    auto tmpIterator = advanceList(iterator, step-1);
    *iterator = *tmpIterator;
    iterator = gl_myList.erase(tmpIterator);

    people--;
}