天天看点

C++中 vector结合迭代器实现增删操作!

1 说明:目的是为了将vector里 符合isdel==true的元素删掉。

2 实现代码

#include "stdafx.h"
#include <assert.h>
#include <time.h>
#include <ObjectArray.h>

using namespace std;

class Test
{
public:
  Test(bool isdel)
  {
    this->is_delete=isdel;
  }
  bool is_delete;
};

void print(vector <Test> &v)
{
  std::vector<Test >::iterator iter;
  for(iter=v.begin();iter!=v.end();++iter)
  {
    cout<<(*iter).is_delete<<" ";
    assert(!(*iter).is_delete);
  }
  cout<<endl;
}

void add(vector <Test> &v,bool b)
{
  Test *t= new Test(b);
  v.push_back(*t);
  delete t;
  cout<<endl;
}

void vec_del(vector <Test> &v)
{
  std::vector<Test >::iterator iter;
  for(iter=v.begin();iter!=v.end();)
  {
    if((*iter).is_delete==true)
    {
      iter=v.erase(iter);
    }
    else
    {
      ++iter;
    }
  }
}

int _tmain(int argc, _TCHAR* argv[])
{
  vector <Test > svec;
  std::vector<Test >::iterator iter;
  srand(time(NULL));

  cout<<"随机赋值:"<<endl;

  for(int i=0;i<100;++i)
  {
    int value=rand()%2;
    add(svec,value);

    cout<<"i="<<i<<" T/F: "<<svec.at(i).is_delete<<endl;
  }
  cout<<endl<<"删除 true:"<<endl;
  vec_del(svec);
  print(svec);
  cout<<endl;
  
  system("pause");
  return 0;
}