简体   繁体   中英

Vector C++ with your own Class

I tried searching in google but it just shows what I'm not looking for.

I have this class called Student and in my main class I instantiated it to be a vector.

I tried adding this line in my main class

vector<Student> students;
students[0].setFirstName("Test");

and it throws an error on my Student class

void Student::setFirstName(string fname) { firstName = fname; }

It says that EXC_BAD_ACCESS. I'm using Xcode in Macintosh

EDIT: I want it to be dynamic that's why I didn't specify the size.

When you create your vector, how many elements are in it? None. And yet you try to access an element right away. You need to put elements in it first. Either at initialization, like this:

vector<Student> students(10);

Or some other method, like push_back , or resize .

As I'm sure you know, the expression students[0] means that you are trying to access to first item in the vector . But in order to access the first item, you must first add a first item.

Quite simply, add a call to vector::push_back before trying to use anything in the vector. Alternatively, declare the vector by

vector<Student> students(/*number of default Students here*/);

There are also other ways, but just make sure you have what you're trying to use.

To be quite specific, the index you pass to the [] operation must satisfy the condition 0 <= index && index < students.size() . In your case, students.size() == 0 , so 0 <= index && index < 0 , which is clearly not possible to satisfy.

Your vector is empty, yet you try to access its first element. Try putting something in the vector before accessing its contents.

You are going out of range for your vector size. You are trying to access an element which doesn't exist. You can declare its size at initialization.

vector<Student> students(SIZE);

As a side note, the setter methods typically take const reference:

void Student::setFirstName(const string &fname) { firstName = fname; } 

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