我试图找到一个元素的索引数组中的字符串索引....我设法使其使用下面的函数整数工作:搜索阵列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