I have the following code and I'm trying to convert the two dimensional array to a two dimensional vector.
int main()
{
const string ID_BASE = "56-123-";
const int NUM_AISLES = 2;
const int NUM_SHELVES = 3;
// Declare 2-D array of objects.
//Product products[NUM_AISLES][NUM_SHELVES];
Product **products;
int idNum = 0;
int i, j;
products = new Product *[NUM_AISLES];
// Add a set of candy bars (all same price).
for (i = 0; i < NUM_AISLES; i++)
{
products[i] = new Product[NUM_SHELVES];
for (j = 0; j < NUM_SHELVES; j++)
{
// Build up id number using string stream.
stringstream id;
id << ID_BASE << setfill('0') << setw(2) << idNum;
products[i][j].set(id.str(), 0.50, true);
idNum++;
}
}
// Increase prices and output each product.
for (i = 0; i < NUM_AISLES; i++)
{
// Increase price for all products in aisle
// (recall products is 2-d, but function
// increasePrice() wants 1-d array).
increasePrice(products[i], NUM_SHELVES, 1.0);
for (j = 0; j < NUM_SHELVES; j++)
{
// Output individual product in 2-d array.
products[i][j].output();
cout << endl << endl;
}
}
Nearly all of my searches about multidimensional vectors are based on primitive data types, and the fact that I'm trying to create a two dimensional vector of objects is tripping me up. Can anyone explain this to me?
I just give you a simple example of initializing a 2D Vector of objects and hope this will help you getting started:
#include <vector>
class Foo {};
typedef std::vector<Foo> FooVector;
typedef std::vector<FooVector> FooMatrix;
main(){
FooMatrix X;
for (int i=0;i<imax;i++){
FooVector Y;
for (int j=0;j<jmax;j++){
Y.push_back(Foo());
}
X.push_back(Y);
}
// ... this is equivalent to ...
FooMatrix X2 = FooMatrix(imax,FooVector(jmax,Foo()));
}
and if have a function that takes a vector:
void bar(FooVector x,int y){ /*...*/ }
you can call it like this:
for (int i=0;i<X2.size();i++){
bar(X2[i],i);
// ... or ...
bar(X2.at(i),i);
}
Hope this helps...
Use a two dimensional vector:
1) you could use vector<vector<Product *>>
products;
vector<vector<Product *> > products;
products[i].push_back(new Product());
Remember to release the objects once done via pointers.
2) you could use vector<vector<Product>>
products;
products[i].push_back(Product());
If you decide to store them by pointers, you must manage allocation/deallocation of these objects.
There are many other things to be taken care of: vector of pointers
On the other hand, storing object by copies in vectors will provide a better locality of reference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.