gpt4 book ai didi

c++ - 数组帮助中插入和修改函数的示例 (c++)

转载 作者:太空狗 更新时间:2023-10-29 21:19:25 27 4
gpt4 key购买 nike

基本上,我已经完成了几乎所有的代码,只是出现了错误,而且我不知道应该删除或添加到这些函数中的内容。我知道他们之间存在某种联系,因为他们的语言应该几乎完全相反。

在 Insert 函数中,它应该检查并查看新条目是否已经存在(如果存在,则函数不返回任何内容),如果条目不存在,则它将条目插入到数组中。

bool ArrayRecord::InsertItem(int item, char* fName, char* lName, double gpa, char* pnum)
{
int location = 0;
// int item;

while (location < length)
{
if (list[location].id == item) return 0;

else {

list[length].id = item;
list[length].firstName = fName;
list[length].lastName = lName;
list[length].gpa = gpa;
list[length].phonenumber = pnum;
length++;
return 1;
/*for the duplicate id prevention search id first if found then return function immediately otherwise start insertion*/
}
}
}

下面是对上述函数的 header 调用:

bool InsertItem(int, char*,char*,double,char*);

现在,这才是真正让我头疼的问题。我去过其他几个论坛,试图在这方面获得帮助,但我对提供给我的帮助感到困惑。修改是先搜索一个词条。如果找到该条目,则修改该条目。如果未找到该条目,则将该条目插入到数组中。

bool ArrayRecord::Modify(int item, char* fName, char* lName, double gpa, char* pnum)
{
int location = 0;
int item; //item has no valid value
while (location < length)
{
//item has no valid value - how do you know it's equal to the id value in the current location?
if (list[location].id == item) return &list[location];
else location++;
}
/*Do a search if it's found then modify the selection but if it's not found then insert a new info*/

}

这里是 header 中用于修改的调用。

    bool Modify(int, char*, char*, double, char*);

这里是错误

Error   1   error C2082: redefinition of formal parameter 'item'    
Warning 2 warning C4800: 'StudentRecord *' : forcing value to bool 'true' or 'false' (performance warning)

我需要用非常简单的语言来理解的示例,并希望对正在发生的事情和我需要做什么进行非常详细的解释。我是初学者,我一直没有练习,所以我忘记了一些东西。我需要澄清。

最佳答案

一些事情:

InsertItem 中的循环只会执行一次,因为 location 在开始时就被取消了。如果您想在添加新项目之前检查项目 ID,函数体应如下所示:

for (int location = 0; location < length; ++location)
if (list[location].id == item) return false;

list[length].id = item;
list[length].firstName = fName;
list[length].lastName = lName;
list[length].gpa = gpa;
list[length].phonenumber = pnum;
length++;

return true;

第二个函数应该不同:

for (int location; location < length; ++location) {
if (list[location].id == item) {
// modify an item
list[location].firstName = fName;
list[location].lastName = lName;
list[location].gpa = gpa;
list[location].phonenumber = pnum;

return false;
}
}

// add new item
list[length].id = item;
list[length].firstName = fName;
list[length].lastName = lName;
list[length].gpa = gpa;
list[length].phonenumber = pnum;

length++;

return true;

在向其中添加新项目或使用 std::vector 之前检查最大列表长度也很好

关于c++ - 数组帮助中插入和修改函数的示例 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27328423/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com