【发布时间】:2014-02-28 02:15:06
【问题描述】:
仅当参数中给出的 sku 字符串与“inventory”数组的成员匹配时,incrementStock 函数才调用“addProduct”函数(该数组的类型为 *Product,大小为 50)。我在构造函数中将数组初始化为 nullptr。 “num”是增量编号。 当我测试它并输入一个有效的 sku 到 incrementStock 时,我从 addproduct 函数中得到“没有空间”。
void Supplier::addProduct(Product *p)
{
bool space = false;
int counter=0;
while(!space && counter < inventory.size() )
{
if(inventory[counter] == nullptr )
{
inventory[counter] = p;
space = true;
}
counter++;
}
if (!space)
{
cout << "no space" << endl;
}
}
void Supplier::incrementStock(const string &sku, int num)
{
bool found = false;
for( int i = 0; i < inventory.size(); i++ )
{
if( inventory[i] && sku == inventory[i]->getSKU())
{
found=true;
addProduct(inventory[i]);
inventory[i]->setQuantity(inventory[i]->getQuantity() +num);
}
}
if (found ==false)
{
cout << "not found" << endl;
}
}
【问题讨论】:
-
为什么不从零长度的库存数组开始,然后只用 push_back() 添加新项目?这样您就不需要进行所有这些搜索和零比较..
-
addProduct总是填充一个新的空槽,即使给定的产品已经存在于inventory中。这是你的意思吗?如果您为同一产品拨打incrementStock50 次,您将填满所有 50 个位置。 -
@Igor Tandetnik:谢谢!你说的方式让我意识到我做错了什么,我实际上不想像我写的那样重新添加同一个成员。
标签: c++ arrays function output