vector中利用迭代器刪除滿足一定條件的元素或者值
阿新 • • 發佈:2019-01-10
#include "stdafx.h" #include <vector> #include <time.h> #include <assert.h> #include<iostream> using namespace std; class TestData { public: TestData(int temp_x) { x=temp_x; is_delete_ = false; } ~TestData() { } void show() { cout<<"x:"<<x<<endl; } int x; bool is_delete_; }; int _tmain(int argc, _TCHAR* argv[]) { int number; int i=0; std::vector<TestData*> m_data; std::vector<TestData*>::const_iterator it; //cout<<"ÇëÊäÈëÄãÒªµÄ¶ÔÏóÊý£º"<<endl; //cin>>number; srand( time(NULL) ); for(i=1;i<=100;i++) { cout<<" #i:"<<i<<" "; int value = rand()%2; TestData *m_test = new TestData(value); m_test->is_delete_ = value; m_test->show(); m_data.push_back(m_test); } cout<<"刪除true之前"<<endl; for(it=m_data.begin();it!=m_data.end();it++) { cout<<(*it)->is_delete_<<" "; } cout<<endl; cout<<"刪除true項"<<endl; for(it=m_data.begin();it!=m_data.end();) { if((*it)->is_delete_==true) { it=m_data.erase(it); //erase刪除元素,就會造成迭代器的失效,所以這裡要重新指定一個迭代器。 } else { ++it; } } cout<<"刪除true之後"<<endl; for(it=m_data.begin();it!=m_data.end();it++) { cout<<(*it)->is_delete_<<" "; assert(!(*it)->is_delete_); } cout<<endl; return 0; }