Daniel
Daniel

Reputation: 179

Declaring a generic iterator

I have the following problem: I need to make a function which takes two iterators and a value and checks if the value is found between the two. The catch: I can only have one template parameter which denotes the type of the elements from the iterators and the value.

My try is like this, but doesn't seem to work:

template <typename T>
T myFind(iterator<std::bidirectional_iterator_tag,T> begin, iterator<std::bidirectional_iterator_tag, T> end, T elem){
// Code
}

But this doesn't work then:

// vector<int> vect; list<string> lst;
myFind(vect.begin(), vect.end(), 15);
myFind(lst.begin(), lst.end(), "some element");

Any ideas? Code after changes:

 template <typename T> 
 T myFind(T begin, T end,typename std::iterator_traits<T>::value_type elem){
   for(T it = begin; it != end; ++it){
     if(*it == elem){
       return it;
     }
    }
    return end;
 }

Upvotes: 1

Views: 147

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

Can you have one template parameter that is the iterator type? If so:

template <typename It>
typename std::iterator_traits<It>::value_type
myFind(It begin, It end, typename std::iterator_traits<It>::value_type elem){
  // ...
}

Otherwise, I think your restriction is too strong.

After your edit: If you want to do - on the iterator that is returned (as you show you do in the comments), you need a random access iterator. However, std::list::iterator is a bidirectional iterator so you can't. You will need to use std::prev (or in C++03, use std::advance).

Upvotes: 1

Related Questions