vector erase

hello guys im just wondering how can i delete vector .

#include "Student.h"

void Student::list()
{
for(int i = 0 ; i < students.size();i++)
{
cout << i+1 << "- " << students.at(i)->getName() << " - " << students.at(i)->getMatrikelnummer() << endl;
}
}

void Student::delete1(int mat)
{int index;
for(int it=0 ; it != students.size(); it++)
{
if(mat == students.at(it)->getMatrikelnummer())
{
index = it;
cout << "im here " << endl;
students.erase(students.erase(students.begin()+index));
}

}

}

int Student::search(int mat)
{
for(int i = 0 ; i < students.size();i++)
{
if(mat == students.at(i)->getMatrikelnummer())
return mat;
}
}

void Student::setMatrikelnummer(int newMat)
{
matrikelnummer = newMat;
}

int Student::getMatrikelnummer()
{
return matrikelnummer;
}

void Student::setName(string newNam)
{
name = newNam;
}

string Student::getName()
{
return name;
}

void Student::setStudent(Student *newStud)
{
students.push_back(newStud);
}


vector<Student*> Student::getStudent()
{
this-> students;
}

///////////////////////////////////////////////////////////////////////////////

#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <vector>
using namespace std;
class Student
{
public:
void list();
void delete1(int);
int search(int);
void setName(string);
void setMatrikelnummer(int);
int getMatrikelnummer();
string getName();
vector<Student*> getStudent();
void setStudent(Student*);
private:
vector<Student*>students;
string name;
int matrikelnummer;
};

#endif



when i run my code , suddenly crash
can someone explain me?
You have a loop of the form:

1
2
3
4
5
    for(int it=0 ; it != students.size(); it++)
    {
        if(mat == students.at(it)->getMatrikelnummer())
            students.erase(students.erase(students.begin()+it));
    }


Consider the loop condition when students has an initial size of 1 and the first (and only) element in the array matches the condition. In that case, one element is removed from the vector in the body of the loop and the for counter is incremented at the conclusion of the loop body. So, for the second iteration of the loop, students.size() evalutes to 0 and it is 1. Since 1 is not equal to 0, the loop continues, and students.at is invoked with an invalid index.
Topic archived. No new replies allowed.