Hi,
I have a std::vector, say myVec, of some user defined object, say
myOb. In my code, I have a function that searches myVec for a
particular myOb.
The way I was doing this was searching myVec for the element that has
a member equal to a value that was passed into the function. For
example:
bool myFunc(const std::string& s)
{
std::vector<myO b>::iterator i = myVec.begin();
while(i != myVec.end()) {
if((*i).name == s) return true;
}
return false;
}
This hopefully returns true if the element is found, or false if not.
However, I don't really want to return true or false, I was wanting to
return either the offset from myVec.begin() (and maybe -1 if not
found), or a reference to the element itself.
How should I do this? Basically, I'm not sure how to return an offset
from begin(), and I didn't know what to return for the reference in
the case of 'element not found'. Or, should I really be returning the
iterator, and de-referencing that in my calling program?
Many thanks for your valued advice,
Bob.
I have a std::vector, say myVec, of some user defined object, say
myOb. In my code, I have a function that searches myVec for a
particular myOb.
The way I was doing this was searching myVec for the element that has
a member equal to a value that was passed into the function. For
example:
bool myFunc(const std::string& s)
{
std::vector<myO b>::iterator i = myVec.begin();
while(i != myVec.end()) {
if((*i).name == s) return true;
}
return false;
}
This hopefully returns true if the element is found, or false if not.
However, I don't really want to return true or false, I was wanting to
return either the offset from myVec.begin() (and maybe -1 if not
found), or a reference to the element itself.
How should I do this? Basically, I'm not sure how to return an offset
from begin(), and I didn't know what to return for the reference in
the case of 'element not found'. Or, should I really be returning the
iterator, and de-referencing that in my calling program?
Many thanks for your valued advice,
Bob.
Comment