[英]Converting a 2d array to 2d vector of objects
我有以下代碼,並且我試圖將二維數組轉換為二維向量。
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()));
}
並且如果具有接受向量的函數:
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());
如果決定通過指針存儲它們,則必須管理這些對象的分配/取消分配。
還有很多其他事情要注意: 指針向量
另一方面,將對象按副本存儲在矢量中將提供更好的參考位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.