-
how to delete from list
Code:
class Person{
public:
string name;
string address;
string phone;
public:
friend ostream& operator<< (ostream& out,const Person& person){
out.setf(ios::left);
out.width(sizeof(person.name)+6);
out<<person.name;
out.width(sizeof(person.address)+6);
out<<person.address;
out.width(sizeof(person.phone));
out<<person.phone<<endl;
return out;
}
friend istream& operator>> (istream& in, Person& person){
in.width(sizeof(person.name)+6);
in>>person.name;
in.width(sizeof(person.address)+6);
in>>person.address;
in.width(sizeof(person.phone)+6);
in>>person.phone;
return in;
}
};
list<Person> L;
list<Person>::iterator i;
bool find (Person pers, const list<Person> &L){
for(list<Person>::const_iterator i = L.begin(); i != L.end(); ++i){
if(((Person)*i).name == pers.name ){
return true;
}
}
}
void deleteR(){
Person person;
cout<<"\nEnter name: ";
cin>>person.name;
if(find(person,L)){
remove(person); dont work...
}
}
how i can.. delete from list..??plz help
-
you have to have the iterator you want to delete and then you type:
L.erase(pos); where L is the list and pos is the iterator (not const_iterator).
e.g.:
list<int> L;
L.push_back(4);
L.push_back(3);
list<int>::iterator pos;
pos = L.begin(); //returns the iterator of the first element
L.erase(pos); //erase the element that the iterator points to
cout << L.size() << ' ' << *(L.begin()) << endl; //should output 1 3
-
if you wanted to remove all occurrences of Persons with that name, you could do
Code:
for(list<Person>::iterator i = L.begin(); i != L.end();){
if(i->name == person.name ){
i = L.erase(i);
} else {
++i;
}
}
or just the first occurrence
Code:
for(list<Person>::iterator i = L.begin(); i != L.end(); ++i){
if(i->name == person.name ){
L.erase(i);
break;
}
}
you get the idea
also, if you need to look up by person's name a lot, and don't need the order, you might consider using a map instead of a list