I am trying to do function that would return postition where occurrence was found in vector. But my return value is always 0 and I’m sure that there is a match.
Here is the code:
int findInItemvector(vector<Item> vec, string name)
{
for(vector<Item>::iterator it = vec.begin(); it < vec.end(); it++)
{
if(it->getName() == name)
{
return it - vec.begin();
break;
}
else
{
return 0;
}
}
}
When your first element does not match, the else branch executes
return, which leaves the function and rest of your loop is not executed. You want something like:However, since first item can also be match (in which case
it - vec.begin() == 0), I suggest you to use other guard value, such as -1 (which can never be valid vector index).