I’m trying to learn cpp and currently tackling arrays. I’m trying to write a function that goes over an array and checks on which index is a specific number. I’m getting an error that says
‘this range-based ‘for’ statement requires a suitable “begin” function and none was found’.
Here is the code:
#include <iostream>
int findIndex(int array[], int value) {
int index = -1;
for(int num : array) {
index = index + 1;
if(num == value) {
return index;
}
}
}
int main() {
int nums[] = {0, 7, 8, 78, 69, 9, 6};
findIndex(nums, 78);
return 0;
}
I tried googling the error as I couldn’t understand it but didnt found anything. If someone can explain it to me I would really appreciate it.
Θοδωρής Ψυχογιός is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
You trying to use iterator and at the same time using index.
The better way for you is to use usual for loop, and don’t touch iterators yet.
Also C arrays (T[]
) doesn’t store any inforamtion about size of array, so you should use vector<T>
instead:
int findIndex(vector<int> array, int value) {
for(int index = 0; index < array.size(); index++) {
if(num == value) {
return index;
}
}
}