【发布时间】:2015-10-09 08:50:42
【问题描述】:
我有以下代码,我正在尝试将二维数组转换为二维向量。
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;
}
}
我几乎所有关于多维向量的搜索都基于原始数据类型,而我正在尝试创建对象的二维向量这一事实让我大吃一惊。谁能给我解释一下?
【问题讨论】:
-
到底是什么问题?只需使用
std::vector<std::vector<Product>> -
... 或
std::array<std::array<Product>>如果您不需要调整大小 -
好的,所以我在外部 for 循环中将其更改为
vector<vector<Product>> products;和products.push_back(vector<Product>());。这应该有效吗?我在increasePrice(products[i], NUM_SHELVES, 1.0);行中的产品出现错误,我不确定这应该是什么。 -
这样调用的话,函数应该是
void increasePrice(std::vector<Products>, ??,??) -
当我尝试
vector<Product>时,我得到了不允许的类型名称。increasePrice定义为void increasePrice(Product incrProds[], int numProds, double amt)