为什么vector的remove_if实际上并没有删除元素,而要配合erase使用
2015-02-10 11:17
483 查看
Erase–remove idiom
Motivation[edit]
A common programming task is to remove all elements that have a certain value or fulfill a certain criterion from acollection. In C++, this could be achieved using a hand-written loop. It is, however, preferred to use an algorithm from the C++ Standard Library for such tasks.[1][2][3]
The algorithm library provides the remove and remove_if algorithms for this. Because these algorithms operate on a range of elements denoted by two forward iterators,
they have no knowledge of the underlying container or collection.[1][4]
Thus, no elements are actually removed from the container. Rather, all elements which don't fit the remove criteria are brought together to the front of the range, in the same relative order. The remaining elements are left in a valid, but unspecified,
state. When this is done, remove returns an iterator pointing one element past the last unremoved element.[4][5]
To actually eliminate elements from the container, remove is combined with the container's
erase member function, hence the name "erase–remove idiom".
Limitation[edit]
Erase–remove idiom cannot be used for containers that return const iterator (e.g.:set)[6]
Example[edit]
// Use g++ -std=c++11 or clang++ -std=c++11 to compile. #include <vector> // the general-purpose vector container #include <iostream> #include <algorithm> // remove and remove_if bool is_odd(int i) { return (i % 2) != 0; } void print(const std::vector<int> &vec) { for (const auto& i: vec) std::cout << i << ' '; std::cout << std::endl; } int main() { // initialises a vector that holds the numbers from 0-9. std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; print(v); // removes all elements with the value 5 v.erase( std::remove( std::begin(v), std::end(v), 5 ), std::end(v) ); print(v); // removes all odd numbers v.erase( std::remove_if(std::begin(v), std::end(v), is_odd), std::end(v) ); print(v); return 0; } /* Output: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 6 7 8 9 0 2 4 6 8 */
相关文章推荐
- remove/remove_if算法配合容器的erase方法实现容器删除元素功能
- (转)vector中使用erase删除元素
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- vector删除元素erase和通用算法remove
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- C++/STL_利用remove_if 删除vector,list,deque满足条件的元素
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- vector删除元素之pop_back(),erase(),remove()
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- vector中使用erase删除元素
- 关于vector中使用erase删除元素后导致越界的问题
- vector用erase删除元素时,为什么被删元素的析构函数会被调用多次?
- vector中使用erase删除元素
- remove与erease配合使用删除元素
- remove() 和 erase()的配合使用和remove()的作用
- STL Vector remove()和erase()的使用
- STL Vector remove()和erase()的使用
- vector用erase删除元素时,被删元素的析构函数会被调用很多次
- erase-remove删除容器元素