- 论坛徽章:
- 0
|
其实我就是想在一次遍历之中删除map中的某些项。
改成这样如何?
#include <iostream>
#include <map>
#include "TestMap.h"
using namespace std;
class TestObject{
private:
int a;
public:
TestObject(int a){
this->a = a;
cout<<"TestObj init.one parameter:a="<<a<<endl;
}
~TestObject(){
cout<<"TestObj desctruction"<<endl;
};
int getA(){
return a;
}
};
void test_map1()
{
cout<<__func__<<endl;
map<int,TestObject *> obj_map;
obj_map[1] = new TestObject(1);
obj_map[2] = new TestObject(2);
obj_map[3] = new TestObject(3);
obj_map[4] = new TestObject(4);
obj_map[5] = new TestObject(5);
obj_map[6] = new TestObject(6);
TestObject *ObjArray[4] = {0,0,0,0};
cout<<endl<<"obj_map size = "<<obj_map.size()<<endl;
int i = 0;
int a = -1;
map<int,TestObject *>::iterator it = obj_map.begin();
for(; it!=obj_map.end();it++ ){
a = it->first;
if (0==(a%2)){
cout<<"erase.a = "<<a<<endl;
ObjArray[i++] = it->second;
obj_map.erase(a);
}
a = -1;
}
cout<<endl<<"obj_map 大小是 "<<obj_map.size()<<endl;
cout<<"删除的个数 "<<i<<endl<<endl;
cout<<"obj_map中对象是:"<<endl;
it = obj_map.begin();
for(; it!=obj_map.end();it++ ){
cout<<it->first<<endl;
}
cout<<endl<<"删除的对象仍然存在,他们是:"<<endl;;
for(i=0; i<4; i++){
if (ObjArray){
cout<<"a="<<ObjArray->getA()<<endl;
}
}
}
void test_map()
{
cout<<__func__<<endl;
map<int,TestObject *> obj_map;
obj_map[1] = new TestObject(1);
obj_map[2] = new TestObject(2);
obj_map[3] = new TestObject(3);
obj_map[4] = new TestObject(4);
obj_map[5] = new TestObject(5);
obj_map[6] = new TestObject(6);
TestObject *ObjArray[4] = {0,0,0,0};
cout<<endl<<"obj_map size = "<<obj_map.size()<<endl;
//遍历删除
int i = 0;
int a = -1;
TestObject *p = NULL;
map<int,TestObject *>::iterator it = obj_map.begin();
while (it!=obj_map.end()){
a = it->first;
p = it->second;
it++;
if (0==(a%2)){
cout<<"erase.a = "<<a<<endl;
ObjArray[i++] = p;
obj_map.erase(a);
}
a = -1;
} //遍历删除
cout<<endl<<"obj_map 大小是 "<<obj_map.size()<<endl;
cout<<"删除的个数 "<<i<<endl<<endl;
cout<<"obj_map中对象是:"<<endl;
it = obj_map.begin();
for(; it!=obj_map.end();it++ ){
cout<<it->first<<endl;
}
cout<<endl<<"删除的对象仍然存在,他们是:"<<endl;;
for(i=0; i<4; i++){
if (ObjArray){
cout<<"a="<<ObjArray->getA()<<endl;
}
}
} |
|