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?

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.

Thank you Narue!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.