abort remove_if of vector

来源:互联网 发布:爱五子棋打谱软件 编辑:程序博客网 时间:2024/06/18 04:57

今天在使用remove_if函数来删除指定的vector元素的时候,发现虽然vector容器中指定的元素被删除了,但是vector容器的大小并没有变,打印出所有的元素发现,vector中未被删除的元素都向前移动了,移动之后,没有元素的位置上默认填充vector中最后的元素值,例如:

code

#include<iostream>using namespace std;#include<vector>#include<algorithm>template <typename T>class Display{    public:        void operator()(const T& x)        {            cout << x <<" ";        }};template <typename T>class Equal{    public:        T m_x;        Equal(const T& ix)        {            m_x = ix;        }        bool operator(const T& x)        {            retrun m_x == x;        }};int main(int argc,char* argv[]){    int arr[] = {1,2,3,4,5};    vector<int> iv(arr,arr+5);    cout << " Before removed: ";    for_each(iv.begin(),iv.end(),Display());    remove_if(iv,begin(),iv.end(),Equal(3));    cout << "After removed: ";    for_each(iv.begin(),iv.end(),Display());    return 0;}

result

Before removed: 1 2 3 4 5 After removed: 1 2 4 5 5 
0 0
原创粉丝点击