template <class ForwardIterator, class UnaryPredicate>ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,UnaryPredicate pred);
std::remove_if函数删除容器中满足pred
的元素,返回最后一个没被移除的元素后面一个迭代器(An iterator to the element that follows the last element not removed.),但是容器的大小是不变的。
假设std::remove_if
返回的迭代器是pend
,虽然容器的大小不变,但是从pend
到容器最后一个元素的值是unspecified state的(The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state.)。
// remove_if example
#include <iostream> // std::cout
#include <algorithm> // std::remove_if
#include <vector>bool IsOdd (int i) { return ((i%2)==1); }int main () {std::vector<int> myints1{1,2,3,4,5,6,7,8,9}; // 1 2 3 4 5 6 7 8 9auto pend1 = std::remove_if (myints1.begin(), myints1.end(), IsOdd); // 2 4 6 8 ? ? ? ? ?// ^ ^/* 奇数被移除了,所以只剩偶数了 */std::cout << "the range contains:";for (auto p=myints1.begin(); p!=pend1; ++p)std::cout << ' ' << *p;std::cout << '\n' << std::endl << "The myints contains: \n";/* 奇数被移除了,剩余的偶数从索引0开始填充,std::vector后面没被填充的元素值可能是原始位置的值,但不保证 */for(auto const &it: myints1){std::cout << it << ", "; }std::cout << std::endl;std::cout << "-------------------------------------------\n";std::vector<int> myints2{1,3,5,7,9,11,13,15,17};auto pend2 = std::remove_if (myints2.begin(), myints2.end(), IsOdd); /* 所有元素都是奇数,都被移除,因此打印为空 */std::cout << "the range contains:";for (auto p=myints2.begin(); p!=pend2; ++p)std::cout << ' ' << *p;std::cout << '\n' << std::endl << "The myints contains: \n";/* myints2中的所有元素都是奇数,都被移除了,因此原容器myints2中的元素都没被替换,因此输出的值可能还是1, 3, 5, 7, 9, 11, 13, 15, 17,但并不能保证值一定是这样 */for(auto const &it: myints2){std::cout << it << ", "; }std::cout << std::endl;return 0;
}
输出:
the range contains: 2 4 6 8The myints contains:
2, 4, 6, 8, 5, 6, 7, 8, 9,
-------------------------------------------
the range contains:The myints contains:
1, 3, 5, 7, 9, 11, 13, 15, 17,