Victor
Victor

Reputation: 14612

Using auto for iterators

I have the following code:

template<typename ty>
bool vector_has(const std::vector<ty> &in_vector, const ty element) {
  for(auto it = std::cbegin(in_vector); it != std::cend(in_vector); it++) 
    if(*it == element) return true;
  return false;
}

I have given the it type of auto. Visual Studio seems not to know what that is (before run)... What is the type of it?

Upvotes: 2

Views: 2621

Answers (2)

Germ&#225;n Diago
Germ&#225;n Diago

Reputation: 7673

begin and cbegin will yield the same kind of iterator for a const vector as input.

On the other side, I think you should use the range-based for loop, since it is less verbose:

template<typename ty>
bool vector_has(const std::vector<ty> &in_vector, const ty element) {
  for(auto const & val : in_vector) 
    if(val == element) return true;
      return false;
}

P.S.: I also recommend that you pass element by const reference to avoid copies: const tv & element.

Upvotes: -1

Baum mit Augen
Baum mit Augen

Reputation: 50061

it has the type std::vector<ty>::const_iterator which is deduced from the return type of std::cbegin(std::vector<ty>).

Upvotes: 3

Related Questions