Connecting Tech Pros Worldwide Forums | Help | Site Map

Having problems with vectors!

Newbie
 
Join Date: Sep 2006
Posts: 3
#1: Sep 30 '06
Hello.

This is the first time I'm encountering vectors and I'm having problems.

I want to create a vector filled with objects, but as soon as I try to invoke a

function within the object,

I get an error message stating "Vector out of subscript range". And I'm using

visual studio 2005.

So for example
int main()
{
vector<student> myStudent; // Vector filled with student objects
myStudent[0].enterGrade(200); // Compiler error
}

I must be missing something very simple yet I can't quite figure out. Any help would be appriciated!

Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,180
#2: Sep 30 '06

re: Having problems with vectors!


You never assign the vector a size and you never assign the vector any objects

vector<student> myStudent; // Vector filled with student objects
creates the vector

myStudent[0].enterGrade(200); // Compiler error
but this tries to access the student object at index [0] before any student object has been created at that index.

You can use

myStudent.push_back( <object> );

to add a specific object to the end of the vector or

myStudent.resize(count);

to set the vector to a give size with each object taking it's default value.
Newbie
 
Join Date: Sep 2006
Posts: 3
#3: Oct 1 '06

re: Having problems with vectors!


Thanks! it works
Reply