vector of objects, deleting
Jan 24, 2014 at 12:48pm UTC
Hi there! i am messing around with vector and classes, and with this program i wrote, i don't understand what is wrong. You can make a new object by pressing 1. and by pressing 2 you *SHOULD* delete all the objects with the name you enter. But it seems like only half of the objects gets deleted!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class monster
{
public :
monster()
{
level = 100;
name = "santa" ;
};
~monster(){};
string getName()
{
return name;
}
private :
int level;
string name;
};
int main()
{
vector<monster>v;
int answer=0;//what to do in menu answer
while (1)
{
cout <<"__________MENU__________" <<endl;
cout <<"1: create new class" << endl ;
cout <<"2: delete class #by name" << endl;
cout <<"_______________________" << endl;
cout <<"#######################" << endl;
cout << "there are: " <<v.size() << " classes" << endl;
cout <<"#######################" << endl;
cin >>answer;
system("cls" );
if (answer ==1)
{
monster *obj_m;
obj_m = new monster;
v.push_back(*obj_m);
delete obj_m;
system("cls" );
}
if (answer==2)
{
string tmp_answer;//wich class is going to be deleted?
int times=0;//counts how many objects has been deleted
cout <<"name of class/classes to delete: " << endl;
cin >> tmp_answer;
system("cls" );
for (unsigned int i=0;i < v.size();i++)
{
if (tmp_answer == v[i].getName())
{
v.erase(v.begin()+i);
times++;
}
}
if (times > 0)
{
cout <<"============================" << endl;
cout <<"amount of objects deleted: " << times << endl;
cout <<"============================" << endl;
}
else
{
cout <<"==============================" << endl;
cout <<"there where no objects deleted" << endl;
cout <<"==============================" << endl;
}
}
if (answer==-1)
{
return 0;
}
}
return 0;
}
Jan 24, 2014 at 1:02pm UTC
But it seems like only half of the objects gets deleted!
The reason for this is that you must not increase
i
after you erased an element. The element i+1 becomes the element i
Jan 24, 2014 at 1:31pm UTC
Oh right! I understand what went wrong now! Thanks :)
Last edited on Jan 24, 2014 at 1:33pm UTC
Topic archived. No new replies allowed.