What is the correct way to implement an efficient 2d vector? I need to store a set of Item objects in a 2d collection, that is fast to iterate (most important) and also fast to find elements.
I have a 2d vector of pointers declared as follows:
std::vector<std::vector<Item*>> * items;
In the constructor, I instantiate it as follows:
items = new std::vector<std::vector<Item*>>();
items->resize(10, std::vector<Item*>(10, new Item()));
I how do I (correctly) implement methods for accessing items? Eg:
items[3][4] = new Item();
AddItem(Item *& item, int x, int y)
{
items[x][y] = item;
}
My reasoning for using pointers is for better performance, so that I can pass things around by reference.
If there is a better way to go about this, please explain, however I would still be interested in how to correctly use the vector.
Edit: For clarification, this is part of a class that is for inventory management in a simple game. The set 10×10 vector represents the inventory grid which is a set size. The Item class contains the item type, a pointer to an image in the resource manager, stack size etc.
My pointer usage was in an attempt to improve performance, since this class is iterated and used to render the whole inventory every frame, using the image pointer.
It seems that you know the size of the matrix beforehand, and that this matrix is squared. Though
vector<>is fine, you can also use native vectors in that case.If you want to access position r,c, then you only have to multiply r by n, and then add c:
So, if you want to access position 1, 2, and n = 5, then:
Also, instead of using plain pointers, you can use smart pointers, such as
auto_ptr(obsolete) andunique_ptr, which are more or less similar: once they are destroyed, they destroy the object they are pointing to.The only drawback is that now you need to call
get()in order to obtain the pointer.Here you have a class that summarizes all of this:
Now you only have to create the class
Item. But if you created a specific class, then you’d have to duplicateItemsSquaredMatrixfor each new piece of data. In C++ there is a specific solution for this, involving the transformation of the class above in a template (hint:vector<>is a template). Since you are a beginner, it will be simpler to haveItemas an abstract class:And derive all the data classes you will create from them. Remember to do a cast, though…
As you can see, there are a lot of open questions, and more questions will raise as you keep unveliling things. Enjoy!
Hope this helps.