문제

I would like to remove an element from a std::vector v using

v.erase( std::remove_if( std::begin(v), std::end(v), pred), std::end(v) );

I know that the removable element (if exist) it must be between index1 and index2. Is there any way to use this information with remove_if?

도움이 되었습니까?

해결책

If there is just one element to removed it seems the approch to go is to use std::find_if() rather than std::remove_if() and locate the object in the specific range:

auto it = std::find_if(v.begin() + index1, v.begin() + index2, pred);
if (it != v.begin() + index2) {
    v.erase(it);
}

If there are potentially more elements you could use

v.erase(std::remove_if(v.begin() + index1, v.begin() + index2, pred), v.begin() + index2);

You can use v.erase() to remove elements from an internal range.

다른 팁

This will only search between index1 and index2, NOT including either index. It's up to you to make sure the range is still valid.

v.erase( std::remove_if( std::begin(v) + index1 + 1, std::begin(v) + index2, pred), v.begin() + index2);
v.erase( std::remove_if( std::begin(v) + index1, std::begin(v) + index2, pred), std::begin(v) + index2 );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top