Reputation: 157
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!
Upvotes: 2
Views: 986
Reputation: 53047
1) Don't pass the iterators in by reference.
Why? Because you can't bind references to rvalue expressions, which begin()
and end()
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.
9
is 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 as count_c<foo::iterator>(...)
if you want to specify the type of iterator.
template<typename iter_t>
int count_c(int i, iter_t start, iter_t end){
int count = 0;
for(iter_t p = start; p != end; p++){
if((*p) == i){
count = count + 1;
}
}
Upvotes: 2
Reputation: 131789
First, you pass 9
(which is of type int
) and that is what Container
gets deduced as. Since int
doesn't have a nested typedef iterator
, SFINAE kicks in. That removes the function from the overload set, and since you have no other function that could be chosen, you are left with no functions to call: the error.
Since this is for exam preparation, I'll only give a hint: Templatize on iterators and value type, not the container type.
Upvotes: 4