开发者

Pointer to vector in a struct C++

I am getting a few crashes related to the fact that I use a vector in my struct that may have to use about 6000 elements. Here is my struct:

struct Students 
{
char* names;
std::vector<int> scores;
};

Is there a way to make it so my vector is not causing my struct to caus开发者_StackOverflow中文版e an error. Here is my calling code.

while(scores.hasNext())
{
    students[current_student].scores.push_back(grade);
}

My question: if this is a problem with size allocation of a vector within a struct, could I declare a pointer to a vector and deference my vector instead of having it actually in the struct?

Grades is just an integer.


You remind me of a similar problem someone here met before. As there is no enough information provided for the rest of your code, I just make a guess here.

Obviously students is an array of structure Students. Assuming it's allocated on the heap, if you do that using malloc, it won't work properly because malloc won't properly initialize the members in the structure. Especially, here scores is a non-POD object and it needs properly constructed by calling its constructor.

// the member in your structure is not initialized
students = (struct Students*) malloc(10 * sizeof(Students));

// oops.. scores is not initialized
students[0].scores.push_back(100);

To solve it, you need call new instead. It'll properly initialize members by calling their constructors.

// ok
students = new Students[10];


If you get some error from vector's code in this line

students[current_student].scores.push_back(grade);

it doesn't mean that the problem is with the vector. what it does mean is that you access invalid memory (not initialized or not allocated). Probably current_student is out-of-bounds of students, or you allocated students by a call to malloc instead of new.

Your question cannot be answered without you giving more of your code.


First of all, you should't think of struct as weird things that need special precautions. They are equivalent to class

Then, as stated in the comments, you should add real code, because if you really do :

while(scores.hasNext())
{
  students[current_student].scores.push_back(grade);
}

then you will keep on adding elements to your vector (if hasNext() works as it sounds) until you get a std::bad_alloc()

And finally, don't worry about the size of your vector : a std::vector is basically already a pointer to a vector in the heap. Your struct will remain "small" not matter how "fat" your vector becomes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜