0

I am trying to load competitor objects (starter) created in main to a ranker object that stores the competitor objects that are read in as an array of pointers to objects that are read in. For some reason it is only reading the first object that is passed in. How can I read all of the objects in from the main function to the storage in the class?

ranker.cpp:

#include "ranker.h"
#include "competitor.h"
#include <stdlib.h>

Ranker::Ranker(int lanes) {
    athlete = new Competitor*[lanes];   // fix
    numAthletes = 0;
    maxAthletes = lanes;
}

int Ranker::addList(Competitor* starter) {
    if (numAthletes < maxAthletes && &starter != NULL) {
        athlete[numAthletes] = starter;
        numAthletes++;

        return numAthletes;
    }
    else
        return 0;
}

Competitor* Ranker::getLane(int lane) {
    for (int i = 0; i < numAthletes; i++) {
        if (athlete[i]->getLane() == lane - 1) {
            return athlete[i];
        }
    }
}

Competitor* Ranker::getFinish(int position) {
    switch(position) {
        case 1:
            return athlete[3];
            break;
        case 2:
            return athlete[2];
            break;
        case 3:
            return athlete[1];
            break;
        case 4:
            return athlete[0];
            break;
    }
}

int Ranker::getFilled() {
    return numAthletes;
}

Ranker::~Ranker() {
    delete athlete;
}

ranker.h:

#ifndef _RANKER_H
#define _RANKER_H

#include "competitor.h"

class Ranker {
private:
Competitor** athlete;
    int numAthletes;
    int maxAthletes;
public:
    Ranker(int lanes);
    int addList(Competitor* starter);
    Competitor* getLane(int lane);
    Competitor* getFinish(int position);
    int getFilled();
    ~Ranker();
};

#endif

part of main function:

for (int i = 0; i < lanes; i++)
    rank.addList(starters[i]);
1
  • 1
    Your first problem is you using pointers, your second problem is also using pointers. Learn more about the C++ standard containers. Commented Jul 19, 2013 at 20:30

1 Answer 1

1

Use a std::vector<Competitor> to store your competitors, and add them with push_back().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.