【发布时间】:2016-11-07 04:29:44
【问题描述】:
所以我有一个输入文件。它由 40 个数字组成。前 20 个数字被输入到一个数组中(我已经检查过了,它们实际上就在那里)。然后我关闭并重新打开输入文件。我使用顺序搜索将输入文件中的前 20 个数字与我的数组进行比较。这意味着他们都应该成功。然后我将接下来的 20 个数字与我的数组中的数字进行比较,它们应该都是不成功的搜索。我的数组此时未排序。
我遇到的问题是,使用顺序永远找不到最后一个成功的数字。我不确定如何解决这个问题。
这里是顺序搜索功能:
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++;
}
}
我在构造函数中将索引初始化为0
这就是我声明数组的方式
ItemType list[length];
它有效!!!!非常感谢大家!我真的很感激。
【问题讨论】:
-
您确实打印错误数组:在当前形式下,您正在打印超出实际数组末尾的元素。我通常使用
for (int i = 0; i < sizeof(list)/sizeof(list[0]); ++i),它会在最后自动停止。另一个问题是您将数组的一个元素定义为短:请记住,在 C 中,数组ItemType list[N]可以从 0 到 N-1 进行索引。 -
是的,这表明我的数组保存了正确的值,谢谢。
-
第一件事:以这种方式声明您的数组会给出一个包含 19 个项目的数组(索引 0 到 18)。如果要声明一个包含 20 个项目(索引 0 到 19)的数组,则需要删除负 1。
标签: c++ search sequential