Why cant you compare the value if an int type variables?
For example:
1 2 3 4 5 6 7 8 9 10 11 12
int a = v.size();
for(int i=0; v[i]!=n && i<a; i++){}
if(i<a){
return i;
}
else{
return -1;
}
This is a part of a function here where i and a are both integers. I wrote the condition for if to be that when the value of i is less than the value of a, it should return the value if i otherwise it returns -1.
when i compile this it says:
error: 'i' was not declared in this scope
What am I doing wrong and what can I change or do to be able to make a condition compare the values of two different int type variables?
Does this mean that now values which are attached to functions in the for loop but which are declared outside the for loop also cant have this value used in the if loop ?
for example for the int variable theindex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int mfind(int n, const std::vector <int>& v){
int a = v.size();
int theindex;
for(int i=0; v[i]!=n && i<a; i++){
theindex = i;
}
if(theindex < a){
return theindex;
}
else{
return -1;
}
}
Some people like to call this game "computer science". A famous quote likens that to calling surgery "knife science", but nonetheless it is still possible sometimes to carry out one of the fundamental operations of a science; to whit, an experiment.
what if the vector vec had more than one number 14 in there? what then would happen?
Repeater is absolutely right, but I'll ask one other thing:
what if the vector vec had more than one number 14 in there? what then would happen?
What would you like to have happen?
Two feasible scenarios in my mind would be (1) returning the first result, or (2) returning a vector of results (or a vector of {index, value} pairs). It's possible to code either one.
Are you referring to Repeater's code?
That's how a return statement works. Once return is called, the function ends. The return -1 is never reached if the if-statement (line 19) is entered.