#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;
}
vector中利用迭代器删除满足一定条件的元素或者值
最新推荐文章于 2024-10-11 17:06:39 发布