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

lim*_*lim 1 c++ iterator vector

我写了这个方法来找到稀疏矩阵的次要:

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;

}
Run Code Online (Sandbox Code Playgroud)

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

问题出在哪儿?

非常感谢.

ere*_*eOn 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.
    }

}
Run Code Online (Sandbox Code Playgroud)


Ben*_*oit 5

erase使迭代器无效.做it = matrix.erase(it)代替.