hi guys,

I've created a function that returns the number of times a value resides in a container (in this case, vector).

The user is able to specify were in the vector they wish to search for the value.

int number(int n, vector<int>::iterator start, vector<int>::iterator end)
{
	int count = 0;
	for(start; start != end; start++)
	{
		if(n == (*start))
			count++;
	}
	return count;
}

However, I'm having an issue when trying to turn this function into a generic one. If I do the following I get an error message "syntax error : identifier 'iterator'".

template <class T>
int number(T n, vector<T>::iterator start, vector<T>::iterator end)
{
	int count = 0;
	for(start; start != end; start++)
	{
		if(n == (*start))
			count++;
	}
	return count;
}

One more question, when calling, is there any way to specify in the vector were to directly start looking instead of writing "v.begin() + 4" / "v.end() - 1" as I'm doing at the moment?

Edited 7 Years Ago by pac-man: n/a

When you changed int to T in the iterator parameters, they became dependent types. You need to specify that iterator refers to a type name:

template <class T>
int number(
  T n, 
  typename vector<T>::iterator start, 
  typename vector<T>::iterator end)
{
  int count = 0;
  for(start; start != end; start++)
  {
    if(n == (*start))
      count++;
  }
  return count;
}

Or you could just use the std::count template function from <algorithm>. It does the same thing as your function.

This question has already been answered. Start a new discussion instead.