我試圖找到一個元素的索引數組中的字符串索引....我設法使其使用下面的函數整數工作:搜索陣列C++
int *getIndexOfInt(int *arr, int size, int check) {
int *result;
int *k;
int count = 0;
for (int i = 0; i <= size - 1; i++) {
if (arr[i] == check) {
k[count] = i;
count++;
}
}
if (count > 0) {
*result = *k;
return result;
} else
cout << "Not Found";
}
然而,當我試圖這個字符串,它只是給了我錯誤或無限循環(具有狀態11退出程序):
int *getIndexOfString(string *arr, int size, string check) {
int *result;
int *k;
int count = 0;
for (int i = 0; i <= size - 1; i++) {
if (arr[i] == check) {
k[count] = i;
count++;
}
}
if (count > 0) {
*result = *k;
return result;
}
else cout << "Not Found";
}
能否請你告訴我爲什麼,也許幫我修復錯誤?
編輯: 結果變量是其然後在主函數使用的陣列,它包含其中的字符串是在給定陣列中找到的索引。 k變量只是一個數組,其中的值在被添加到結果中之前被存儲。 arr是給定的字符串數組,大小是givven大小,check是代碼將搜索的字符串。
乍一看錶明,您的第一個功能不起作用。 'int * k'和'int * result'永遠不會被初始化。 – yngccc
然後我有另一個問題。第一個爲什麼工作? – SpiderLinked
如果這不是訓練目的,我會建議使用['std :: find'](http://en.cppreference.com/w/cpp/algorithm/find)。 – Nobody