[英]Don't know why getting segmentation fault
我正在嘗試在Xcode中使用C ++解決Grid Search ,並產生一些奇怪的輸出。
我的代碼:
#include <iostream>
#include <vector>
using namespace std;
int main(){
int tCases;
cin >> tCases;
for(int i = 0; i < tCases; i++){
bool isFound = false;
int row = 0, column = 0, tRow = 0, tColumn = 0, p = 0;
cin >> row >> column;
vector<string> matrix(row);
for (int i = 0; i < row; i++) {
cin >> matrix[i];
}
cin >> tRow >> tColumn;
vector<string> tMatrix(tRow);
for (int i = 0; i < tRow; i++) {
cin >> tMatrix[i];
}
vector<long> position(tRow);
for (int i = 0; i <= row - tRow; i++) {
position[p] = matrix[i].find(tMatrix[p]) ;
if (position[p] == string::npos) {
isFound = false;
p = 0;
}
else if (p != tRow && (p == 0 || position[p] == position[p-1])) {
isFound = true;
p++;
}
else if (p == tRow)
break;
}
cout << (isFound ? "YES" : "NO") << endl;
}
return 0;
}
測試用例1:
1
20 20
34889246430321978567
58957542800420926643
35502505614464308821
14858224623252492823
72509980920257761017
22842014894387119401
01112950562348692493
16417403478999610594
79426411112116726706
65175742483779283052
89078730337964397201
13765228547239925167
26113704444636815161
25993216162800952044
88796416233981756034
14416627212117283516
15248825304941012863
88460496662793369385
59727291023618867708
19755940017808628326
7 4
1641
7942
6517
8907
1376
2691
2599
我的輸出和預期輸出:
沒有
測試案例2:
1
25 25
7652157548860692421022503
9283597467877865303553675
4160389485250089289309493
2583470721457150497569300
3220130778636571709490905
3588873017660047694725749
9288991387848870159567061
4840101673383478700737237
8430916536880190158229898
8986106490042260460547150
2591460395957631878779378
1816190871689680423501920
0704047294563387014281341
8544774664056811258209321
9609294756392563447060526
0170173859593369054590795
6088985673796975810221577
7738800757919472437622349
5474120045253009653348388
3930491401877849249410013
1486477041403746396925337
2955579022827592919878713
2625547961868100985291514
3673299809851325174555652
4533398973801647859680907
5 4
5250
1457
8636
7660
7848
我的輸出和預期輸出:
是
有趣的是,當我嘗試同時檢查兩個測試用例時,它只是為我提供了第一個測試用例的輸出,然后繼續運行而不顯示任何內容。 HackerRank表示存在細分錯誤。 但是,我在CLion中運行了組合測試用例,並且運行良好。 您能幫我找到代碼中的錯誤嗎?
for (int i = 0; i <= row - tRow; i++)
{
position[p] = matrix[i].find(tMatrix[p]) ;
if (position[p] == string::npos)
{
isFound = false;
p = 0;
}
else if (p != tRow && (p == 0 || position[p] == position[p-1]))
{
isFound = true;
p++;
}
else if (p == tRow)
break;
}
}
這可能會導致段錯誤:
如果p
達到tRow-1
(為什么不!),然后如果position[p] == string::npos
(為什么不!),則輸入第一個else if
語句並執行: isFound = true; p++;
isFound = true; p++;
然后,在下一次迭代中, p
是tRow
(隨着它的增加),然后將進行測試(position[p] == string::npos)
。 在tRow
索引處的訪問position
,該position
已超出范圍。
循環條件
for (int i = 0; i <= row - tRow; i++)
應該替換為
for (int i = 0; (i <= row - tRow) && (p < tRow); i++)
防止這種情況。 然后可以簡單地刪除else
語句( if (p == tRow) break;
)。
你一個人走。
更換
else if (p == tRow)
break;
通過
if (p == tRow)
break;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.