I’m having some difficulties with the below generic function, I want this function to take 2 iterators and a value. The function should iterate between the 2 iterators and check for any occurrences of the value and count the occurrences. But I get the following error:
no matching function for call to ‘count_c(int, std::vector::iterator, std::vector::iterator)’
template<typename Container>
int count_c(Container i, typename Container::iterator &start, typename Container::iterator &end){
typedef typename Container::iterator Iter;
int count;
for(Iter p = start; p != end; p++){
if((*p) == i){
count = count + 1;
}
return count;
}
int main(){
vector<double> myv;
myv.push_back(9);
myv.push_back(10);
count_c(9, myv.begin(), myv.end());
return 0;
}
It’s part of an exam question:
Write a generic function count which:
Takes as parameters a value and two iterators of a container (where to start from and
where to finish in the container).It uses the iterators to go through the elements of the container and count the occur-
rences of the value in the container.Finally, it returns the number of occurrences of the value it has found.
The two iterators are not necessarily the same as what is returned by a con-
tainer’s begin() and end() methods!
1) Don’t pass the iterators in by reference.
Why? Because you can’t bind references to rvalue expressions, which
begin()andend()are. Besides, there’s not much point in doing so, as iterators are very small and faster to copy by value.2) Use the iterator type, not the container.
9is not a container, and so lacks an iterator type. There is no reason to need the container, as iterators were designed to work without them. Some iterators don’t even have a container, such as plain ol pointers. You can always call your function ascount_c<foo::iterator>(...)if you want to specify the type of iterator.