所以我有一個輸入文件。它由40個數字組成。前20個數字被輸入到一個數組中(我已經檢查過,他們實際上在那裏)。然後關閉並重新打開輸入文件。我使用順序搜索將輸入文件中的前20個數字與我的數組進行比較。這意味着他們都應該成功。然後,我將下面的20個數字與我數組中的數字進行比較,它們都應該是不成功的搜索。我的數組在這一點上是未排序的。C++順序搜索沒有找到最後一個元素
我遇到的問題是,成功的最後一個號碼永遠不會使用順序找到。我不知道如何解決這個問題。
這裏是順序搜索功能:
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
如果我刪除「如果(找到)」聲明一切正常,但我如何解決這個問題而不刪除?
在此先感謝
---------------編輯---------------
好吧,當我改變長度到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];
IT WORKS !!!!非常感謝你們!我非常感激。
你打印你數組不正確:在當前形式中,您正在打印實際數組末尾的元素。我通常使用`for(int i = 0; i
Lars
2010-12-09 16:42:58
是的,這表明我的數組保存了正確的值,謝謝。 – 2010-12-09 16:55:24