What would be the bast way to insert and remove elements of a vector by iterating from the end

111 views Asked by At

I'm currently refactoring some really old code and I would like to make it the most C++11 possible ( we don't use C++14 of 17 yet, but it's coming ) mostly as an academic example.

The code is looping from the end of a vector and displaces some of the elements after the current element of the vector.

Here is the code I came up with ( removed a lot of irrelevant parts ):

const size_t N = m_ObjVec.size();
size_t idx = N-1;
for ( ; ; )
{
    CObj& curObj = *m_ObjVec[ idx ];

    size_t otherIdx = FindOther( idx, N );

    if ( c_NPOS != otherIdx )
    {
        CObj* pOtherObj = m_ObjVec[ otherIdx ];

        // insert pOther after idx
        m_ObjVec.insert( m_ObjVec.begin()+idx+1, pOtherObj );
        // erase pOther from vector
        m_ObjVec.erase( m_ObjVec.begin()+otherIdx );
    }
    else
    {
        if ( 0 == idx-- ) break;
    }
}

I tried using reverse iterators with little success. I cannot use them with the erase / remove_if idiom nor can I use them in a loop where I insert.

What I'd like to write is basically "reverse_move_after_if".

NOTE It has to loop from the end, only once. Looks a lot like a sort but it's not if you take those contraints into account.

0

There are 0 answers