user1869173
user1869173

Reputation: 11

Accessing vector in class in vector

I feel as though I'm going about this the right way, but I keep getting the error "EXC BAD ACCESS"

I have a class person, fairly simple with everything public.

class person
{
    public:
    int id;
    vector<float> scores;
    float avgscore;
};

I then make a vector of persons using the new operator

vector<person> *people = new vector<person>[num_persons];

I then attempt to access the vector inside the class person

(*people)[current_person].scores.push_back(temp);

where current_person =0, and temp is an integer.

Am I handling the vector the right way?

Upvotes: 1

Views: 989

Answers (2)

billz
billz

Reputation: 45410

This line

vector<person> *people = new vector<person>[num_persons];

new vector only creates a vector but it contains 0 elements, accessing to (*people)[0] is undefined behavior which your error message EXC BAD ACCESS tells the story. You still need to add person element to people visiting it, e.g.

person p1;
people->push_back(p1);  // add element to vector
(*people)[0].scores.push_back(temp); // now you are ok to visit first element.
// don't forget to delete vector at right place
delete people;

As you are using vector already, you could just continue using vector for people instead of using the raw pointer.

std::vector<person> people;
person p1;

people.push_back(person);
people[position].scores.pus_back(score);
// don't need to worry releasing people memory anymore.

Upvotes: 1

combinatorial
combinatorial

Reputation: 9561

Try this:

vector<person> people(num_persons);

and then...

people[current_person].scores.push_back(temp);

Upvotes: 2

Related Questions