简体   繁体   中英

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 person s 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?

Try this:

vector<person> people(num_persons);

and then...

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

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, eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM