gpt4 book ai didi

C++顺序搜索找不到最后一个元素

转载 作者:行者123 更新时间:2023-11-30 03:09:06 26 4
gpt4 key购买 nike

所以我有一个输入文件。它由40个数字组成。前 20 个数字被输入到一个数组中(我已经检查过了,它们实际上在那里)。然后我关闭并重新打开输入文件。我使用顺序搜索将输入文件中的前 20 个数字与我的数组进行比较。这意味着他们都应该成功。然后我将接下来的 20 个数字与我数组中的数字进行比较,它们应该都是不成功的搜索。我的数组此时未排序。

我遇到的问题是,使用 sequential 从未找到表示成功的最后一个数字。我不确定如何解决这个问题。

这里是顺序搜索函数:

length = 19;

void Search::sequential(ItemType item, bool& found)
{
int place = 0;
while (place < length && item != list[place])
place++;
found = (place < length);
}

这是我成功/不成功的循环

outFile << "\n\n ************Sequential Successful ********** \n";
outFile << endl << "ID" << endl;

inFile >> num;
for(int i=0; i<=length && inFile; i++)
{
search.sequential(num, found);
if (found)
outFile << num << endl;

inFile >> num;
}


//sequential unsuccessful
outFile << "\n\n ************Sequential unsuccessful ********** \n";
outFile << endl << "ID" << endl;

for(int i=0; i<=length && inFile; i++)
{
search.sequential(num, found);
if (!found)
outFile << num << endl;

inFile >> num;
}

但是,我的输出是:

 ************Sequential Successful ********** 

ID
1111
3352
4567
5678
6789
7890
8901
9012
1223
2113
8546
2374
4723
9573
3284
7474
8594
3589
5858
//THERE SHOULD BE 1925 HERE BUT THERE ISN'T

************Sequential unsuccessful **********

ID
9456
3584
2222
4319
4477
5710
5497
1502
1599
1504
1506
9943
8833
9944
6678
5555
5660
9911
6130
1613

如果我删除“if (found)”语句,一切正常,但如何在不删除它的情况下解决这个问题?

提前致谢

----------------编辑----------------

好吧,当我将长度更改为 20 时,它似乎仍然不起作用。我迷路了。

这里是我创建数组的地方

inFile >> num;
for (int i=0; i<length && inFile; i++)
{
search.addToList(num);
inFile >> num;
}

这里是 addToList 函数

 void Search::addToList(ItemType num)
{
if (index < length) //ive tried taking out this statement just to see if it makes a difference and it didn't
{
list[index] = num;
index++;
}
}

我在构造函数中将index初始化为0

这是我声明数组的方式

    ItemType list[length]; 

它起作用了!!!!非常感谢大家!非常感谢。

最佳答案

有两种解决方案:长度应为 20 作为值

length = 20;

使用“<=”而不是“<”(在这种情况下,“length”应命名为“lastIndex”)

void Search::sequential(ItemType item, bool& found) 
{
int index = 0;
while (index <= length && item != list[index])
index++;
found = (index <= length);
}

关于C++顺序搜索找不到最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4399850/

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