Hey all,
I want to add a vector to my inventory class so that it can hold whichever item data type is passed in. I'm having trouble with setting the size of the vector so that I can put items in it. Here's my code.. Whenever I run it I get output 0, meaning the size of the vector isn't registering.. any help is appreciated.

class inventory
{
public:
	vector <Potion*> potions;

	inventory(int index) : potions (index)
	{
	}	
};

int main()
{
	ePotion energy_potion;
	inventory bag(4);
	bag.potions.assign(0, &energy_potion);
	cout << bag.potions.size();

	cin.get();
	return 0;
}

I found that line

bag.potions.assign(0, &energy_potion);

causes the error, but why? I'm under the thought that this puts the ePotion into the 0th index of the potions vector.. :s

The assign function is used to completely overwrite the entire content of the vector. The overload that you are using (with an integer first and an element value second) is the overload that interprets the first parameter as the number of elements in the new vector content, and the second parameter as the value that should fill the vector. With your use, you are simply setting the vector to have 0 elements.

To read/write a particular value in a vector, you do like with a normal array, with []. As so:

bag.potions[0] = &energy_potion;

You may find it easier to implement your own operator[] instead of exposing the internals of your class. Something along the lines of:

class Inventory {
   std::vector< Potion * > potions;
public:
   Inventory (size_type size) : potions(size) {}
   Potion*& operator[] (size_type index) { return potions[index]; }
};

Which allows for things like:

Inventory bag(4);
bag[0] = new Potion();

Thank you guys for clarifying that! I did what L7Sqr suggested and it worked perfectly, also is a lot neater. Now to expand on this... Thank you for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.