Does iterator + support the operator?

I saw the following code used to remove one selected item from std::vector:

vector<hgCoord>::iterator it;
int iIndex = 0;
    const int iSelected = 5;
for( it = vecPoints.begin(); it != vecPoints.end(); ++it, ++iIndex )
{
    if( iIndex == iSelected )
    {
        vecPoints.erase( it );
        break;
    }
}

I maintain that this code is inefficient and should be written as follows:

vector<hgCoord>::iterator it;
int iIndex = 0;
    const int iSelected = 5; // we assume the vector has more than 5 elements.

    vecPoints.erase( vecPoints.begin() + iSelected );

However, I'm not sure if this code complies with the STL C ++ standard.

+5
source share
4 answers

To make this code generic, it therefore works regardless of whether it supports the iterator operator +and uses the most efficient implementation available:

template <typename C>
void erase_at(C& container, typename C::size_type index) {
    typename C::iterator i = container.begin();
    std::advance(i, index);
    container.erase(i);
}

std::advance operator +, . (, std::list<>::iterator) , , .

+12

, std::vector - .

+10

:)

+2

, , , . (, deque map).

, , , , .

+1

All Articles