我正在尝试解决以下考试问题,但我遇到了困难。
Write a C++ function
find_elem
that takes two iterators first and last of some sequence of elements of typeT
and an objectobj
of typeT
. It returns the iterator to the first occurrence ofobj
in the range (first
,last
), or the iterator last ifobj
is not in the sequence. (35%)NOTE:
first
&last
are 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()
!
这是我的尝试
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;
}
}
这种尝试是否正确?返回类型适合函数还是我理解错了?
最佳答案
是的,您的代码是正确的。我可能只会将 Obj &obj
更改为 Obj const &obj
。
你应该声明p
。
更挑剔:对于通用迭代器,通常首选 ++p
形式。
我的变体(基本相同):
template<typename Iter, typename Obj>
Iter find_element(Iter iter1, Iter iter2, Obj const &obj)
{
for(; iter1 != iter2; ++iter1)
{
if(*iter1 == obj)
break;
}
return iter1;
}
关于c++ - 关于迭代器和泛型函数的考试题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631124/