在迭代c ++期间擦除向量中的元素

时间:2010-10-08 13:48:50

标签: c++ vector iterator

我编写了这个方法来查找稀疏矩阵的次要内容:

SpMatrixVec SparseMatrix::minor(SpMatrixVec matrix, int col) const{

    SpMatrixVec::iterator it = matrix.begin();

    int currRow = it->getRow();

    int currCol = col;

    while(it != matrix.end()) {

        if(it->getRow() == currRow || it->getCol() == currCol){
            matrix.erase(it);
        }
        // if we have deleted an element in the array, it doesn't advance the
        // iterator and size() will be decreased by one.
        else{   
            it++;
        }

    }

    // now, we alter the cells of the minor matrix to be of proper coordinates.
    // this is necessary for sign computation (+/-) in the determinant recursive
    // formula of detHelper(), since the minor matrix non-zero elements are now
    // in different coordinates. The row is always decreased by one, since we
    // work witht he first line, and the col is decreased by one if the element
    // was located after 'col' (which this function receives as a parameter).

    //change the cells of the minor to their proper coordinates.
    for(it = matrix.begin(); it != matrix.end(); it++){

        it->setRow(it->getRow()-1);

        int newY;
        newY = (it->getCol() > col) ? it->getCol() + 1 : it->getCol();

        it->setCol(newY);
    }
    return matrix;

}

现在,我可能做错了,因为当达到while循环的第二次交互时,程序崩溃了。 基本的想法是遍历向量,看看它是否是相关坐标,如果是 - 删除它。我只有在没有删除的情况下才增加迭代器(在这种情况下,向量应该更新迭代器以指向下一个元素。无论如何我都错了)。

问题出在哪里?

非常感谢。

3 个答案:

答案 0 :(得分:9)

erase()使您的迭代器失效。

您必须使用it的返回值更新erase()才能使循环生效:

while(it != matrix.end()) {

    if(it->getRow() == currRow || it->getCol() == currCol){
        //matrix.erase(it);
        it = matrix.erase(it); // Here is the change
    }
    // if we have deleted an element in the array, it doesn't advance the
    // iterator and size() will be decreased by one.
    else{   
        //it++;
        ++it; // ++i is usually faster than i++. It's a good habit to use it.
    }

}

答案 1 :(得分:5)

erase使您的迭代器失效。请改为it = matrix.erase(it)

答案 2 :(得分:-2)

当您在元素之间进行迭代时,无法更改集合。 使用另一个临时集合来存储部分结果。

编辑:更好的是,使用仿函数删除元素:remove_if 你写了条件。