c++ - 关于迭代器和泛型函数的考试题

标签 c++ iterator

我正在尝试解决以下考试问题,但我遇到了困难。

Write a C++ function find_elem that takes two iterators first and last of some sequence of elements of type T and an object obj of type T. It returns the iterator to the first occurrence of obj in the range (first, last), or the iterator last if obj is not in the sequence. (35%)

NOTE: first & last are not necessarily the same as what is returned by a container’s begin() and end() 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 of end()!

这是我的尝试

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/

相关文章:

c++ - vector<bool> 迭代器有任何保证吗?

c++ - 警告 : zero as null pointer constant while comparing iterators

c# - 如何加载多个mscorlib.dll并分别调用它们的内部函数?

c++ - 使用 cout 时发出奇怪的哔哔声

c++ - 在XCode 7.0.1中设置VTK 6.1

c++ - 如何一致地定义同时用作枚举、整数和字符串的选项列表?

c++ - 使用 this = new Foo()? 从内部将一个对象的实例设置为另一个对象的实例?

loops - 为什么这不是一个有效的表迭代器?

基于现有随机访问迭代器的C++反向迭代器?

c++ - 这个语句 "auto iter = first"发生了什么