I want to read all the numbers in a string in a short way of code. I tried like this:
#include <string>
#include <algorithm>
unsigned countNumbers(const std::string s) {
return count_if(s.begin(), s.end(), isdigit);
}
Error message:
a.cc: In function ‘unsigned int countNumbers(std::string)’:
a.cc:5:45: error: no matching function for call to ‘count_if(std::basic_string<char>::const_iterator, std::basic_string<char>::const_iterator, <unresolved overloaded function type>)’
a.cc:5:45: note: candidate is:
/usr/include/c++/4.6/bits/stl_algo.h:4607:5: note: template<class _IIter, class _Predicate> typename std::iterator_traits<_InputIterator>::difference_type std::count_if(_IIter, _IIter, _Predicate)
I know that the count_if () function wants: bool (* f) (char); as the third argument, so I tried using the function:
unsigned countNumbers(const std::string s) {
return count_if(s.begin(), s.end(), reinterpret_cast<bool (*)( char )>(isdigit));
}
Error message:
a.cc: In function ‘unsigned int countNumbers(std::string)’:
a.cc:5:80: error: overloaded function with no contextual type information
I tried an even longer version that gives the same compilation error:
unsigned countNumbers(const std::string s) {
typedef bool ( * f_ptr )( char );
f_ptr ptr = reinterpret_cast<f_ptr>(isdigit);
return count_if(s.begin(), s.end(), ptr);
}
The solution I want to avoid is to create a function that will be an adapter:
#include <string>
#include <algorithm>
bool is_digit(char c) {
return isdigit(c);
}
unsigned countNumbers(const std::string s) {
return count_if(s.begin(), s.end(), is_digit);
}
My question is: how can I use int (* f) (int) functions in std :: algorithms that want bool (* f) (int) without creating adaptation functions and without using lambda expressions?
I have more problems to be solved when I learn how to solve the problem, for example:
- Check if the string is available: find_if_not (s.begin (), s.end (), isprint)
- , ",.!?...": find_if (s.begin(), s.end(), ispunct)
...
, ++ std:: algorithmms
, ,