I’m attempting to solve the below exam question but I’m having difficulties with it.
Write a C++ function
find_elemthat takes two iterators first and last
of some sequence of elements of typeTand an objectobjof typeT. It
returns the iterator to the first occurrence ofobjin the range
(first,last), or the iterator last ifobjis not in the sequence.
(35%)NOTE:
first&lastare not necessarily the same as what is returned by
a container’sbegin()andend()methods! The only thing we suppose is
that the container is some sort of a sequence (e.g., vector, list,
etc.) and that first is an iterator which points to an element which
comes before the one pointed to by last. You must not dereference last
because it might be the result ofend()!
Here’s my attempt
template<typename Iter, typename Obj>
Iter find_element(Iter iter1, Iter iter2, Obj &obj){
for(p = iter1; p != iter2; p++){
if((*p) == obj){
return p;
}
return iter2;
}
}
Is this attempt correct? Is the return type suitable for the function or have I got the wrong idea?
Yes, your code is correct. I would perhaps only change
Obj &objtoObj const &obj.And you ought to have declared
p.More nitpicking: with generic iterators usually the form
++pis preferred.My variant (basically the same):