Does pop_back() really invalidate *all* iterators on an std::vector?

前端 未结 11 1751
半阙折子戏
半阙折子戏 2021-01-05 06:26
std::vector ints;

// ... fill ints with random values

for(std::vector::iterator it = ints.begin(); it != ints.end(); )
{
    if(*it < 10)
         


        
11条回答
  •  死守一世寂寞
    2021-01-05 06:52

    You might want to consider using the return value of erase instead of swapping the back element to the deleted position an popping back. For sequences erase returns an iterator pointing the the element one beyond the element being deleted. Note that this method may cause more copying than your original algorithm.

    for(std::vector::iterator it = ints.begin(); it != ints.end(); )
    {
        if(*it < 10)
            it = ints.erase( it );
        else
            ++it;
    }
    

    std::remove_if could also be an alternative solution.

    struct LessThanTen { bool operator()( int n ) { return n < 10; } };
    
    ints.erase( std::remove_if( ints.begin(), ints.end(), LessThanTen() ), ints.end() );
    

    std::remove_if is (like my first algorithm) stable, so it may not be the most efficient way of doing this, but it is succinct.

提交回复
热议问题