Reputation: 1
so what am trying to do is make a multiple objects using vector. Now my program works fine if i dont use vector and if i have only one object. so how can i have my BoxOfProduce class have more then once object using vectors. i tried what ur seeing infront of u and it works but the program then crashes and says not responding. i know i have to use the push back thing somewhere but have no idea where. i only posted the main function so you dont have to see the whole program because its too big.
int main()
{
int x;
int size;
vector<BoxOfProduce>box;
cout<<"How many boxes you want";
cin>>size;
for ( x = 0; x < size; x++)
{
box[x].setItemAry();
box[x].randomPick();
box[x].display();
box[x].change();
box[x].display2();
}
//BoxOfProduce box;
//box.setItemAry();
//box.randomPick();
//box.display();
//box.change();
//box.display2();
getchar();getchar();
return 0;
}
Upvotes: 0
Views: 94
Reputation: 4805
You can also do like this,
vector<BoxOfProduce>box;
cout<<"How many boxes you want";
cin>>size;
for ( x = 0; x < size; x++)
{
BoxOfProduce obj; //create an object
box.push_back(obj); //insert it into the vector
}
for ( x = 0; x < size; x++)
{
box[x].setItemAry();
box[x].randomPick();
box[x].display();
box[x].change();
box[x].display2();
}
Upvotes: 0
Reputation: 16086
You need to create your object and place them into the vector:
vector<BoxOfProduce> boxes;
for (int i = 0; i < 10; i++)
{
BoxOfProduce box;
box.setItemAry();
box.randomPick();
box.display();
box.change();
box.display2();
boxes.push_back(box); // Put a box into your vector
}
Upvotes: 0
Reputation: 7625
You are accessing the objects in the vector without creating them. Your code should be like this:
for ( x = 0; x < size; x++)
{
BoxOfProduce obj; //create an object
obj.setItemAry();
obj.randomPick();
//.. set other properties
box.push_back(obj); //insert it into the vector
}
vector<BoxOfProduce>box;
will just create a vector, but it does not contain any BoxOfProduce
object. So when you try to access the objects, program crashes.
Upvotes: 2