简体   繁体   English

从std :: vector移除元素

[英]Removing element from std::vector

I would like to remove an element from a std::vector v using 我想使用以下方法从std :: vector v中删除元素

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. 我知道可移动元素(如果存在)必须在index1和index2之间。 Is there any way to use this information with remove_if? 有什么办法可以将这些信息与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: 如果只有一个要删除的元素,似乎可以采用的方法是使用std::find_if()而不是std::remove_if()并将对象定位在特定范围内:

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. 您可以使用v.erase()从内部范围中删除元素。

This will only search between index1 and index2, NOT including either index. 这只会在index1和index2之间搜索,不包括任何一个索引。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM