将2d数组转换为2d对象向量

Converting a 2d array to 2d vector of objects

本文关键字:2d 对象 向量 转换 数组      更新时间:2023-10-16

我有以下代码,我试图将二维数组转换为二维向量。

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;
        }
    }

几乎我所有关于多维向量的搜索都是基于基本数据类型的,而我试图创建对象的二维向量这一事实让我很困惑。有人能给我解释一下吗?

我只是给你一个简单的例子来初始化对象的2D矢量,希望这将帮助你开始:

#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()));
}

和if有一个接受vector的函数:

void bar(FooVector x,int y){ /*...*/ }

你可以这样调用它:

for (int i=0;i<X2.size();i++){
     bar(X2[i],i);
     // ... or ...
     bar(X2.at(i),i);
}

使用二维向量:

1)你可以使用vector<vector<Product *>>产品;

vector<vector<Product *> > products;
products[i].push_back(new Product());

记住,一旦通过指针完成,就释放对象。

2)可以使用vector<vector<Product>>产品;

products[i].push_back(Product());

如果你决定用指针存储它们,你必须管理这些对象的分配/释放。

还有很多其他的事情要注意:指针向量

另一方面,在vector中通过副本存储对象将提供更好的引用位置。