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