user3106529
user3106529

Reputation: 1

while creating and adding objects to a vector in a loop always adds same object

I got a problem,

class student {
public:
    static int id,a,c;
    static bool editable;
    static std::queue <int> classes;
    static queue <int> classesT;
    static queue <int> classesD;
public:
    student(int x,int y,queue <int> z){
        editable=true;
        id=x;
        a=y;
        classes=z;
        c=classes.size();
    }

    void DisposeObject()
    {
       delete this;
    }
};

int main(){
std::vector <queue <int> >links;
std::vector <int> quotas;
std::vector <student> sList;
std::queue <int> classes;
std::queue <student> q1;
int a,c,sNum,cNum;
static int temp;
ifstream myFile("....");
if(myFile.is_open()){
    myFile>>sNum;
    myFile>>cNum;
}
for(int i=0;i<sNum;i++){
    myFile>>c;
    myFile>>a;
    for(int j=0;j<c;j++){
    myFile>>temp;
    classes.push(temp);
    }
    student *s1=new student(i,a,classes);
    sList.push_back(*s1);
    s1->DisposeObject();
    while(!classes.empty())
        classes.pop();
}

This is my code. I want to add different objects to my vector but whenever a new student created students that created before take its values and I end up with a vector something like:

a,a,a,a

instead of

a,b,c,d

By the way I already tried reserve function.

Upvotes: 0

Views: 352

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154045

The code isn't sufficient to pin-point exactly what the problem is. However, there are multiple things which are, at least, suspicious:

  1. You don't check any of your inputs and just assume everything went well! My personal guess is that reading failed at the end of the first or the beginning of the second record and you just reuses the already read values. You always want to check your reads after you attempted to read, e.g.:

    if (myFile >> a >> c) {
         // carry on
    }
    else {
        std::cout << "ERROR: failed to read record!\n";
        // recover, bail out, ...
    }
    
  2. In C++ you don't allocate objects on the heap unless you absolutely have to! Most of the time, you get away with some classes doing the allocation for you. I can't remember when I last used new in application code. Here is how you can append a student record:

    sList.push_back(student(i, a, classes));
    

    The object will, conveniently, clean-up after itself. That is, quickly, get rid of your DisposeObject() member function! C++ uses destructors and neatly do so because it isn't garbage collected. Do not try to carry over C# idioms to C++: it won't do you any good.

  3. There is no need to remove every object individually from your vector. Just use clear():

    classes.clear();
    

Upvotes: 1

Related Questions