can anyone tell me what is the mistake in this program
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string str = "Now";
transform(str.begin(), str.end(), str.begin(), toupper);
cout<<str;
return 0;
}
Error:
"no matching function for call to 'transform(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)'
compilation terminated due to -Wfatal-errors."
There are two functions with name toupper
. One from cctype
header:
int toupper( int ch );
And second from locale
header:
charT toupper( charT ch, const locale& loc );
Compiler can't deduce which function should be used, since you allow namespace std
. You should use scope resolution operator(::
) to choose function defined in global space:
transform(str.begin(), str.end(), str.begin(), ::toupper);
Or, better: Do not use using namespace std
.
Thanks to @Praetorian -
This is probably the cause of the error, but adding
::
may not always work. If you includecctype
toupper
is not guaranteed to exist in the global namespace. A cast can provide the necessary disambiguationstatic_cast<int(*)(int)>(std::toupper)
So, the call should look like:
std::transform
(
str.begin(), str.end(),
str.begin(),
static_cast<int(*)(int)>(std::toupper)
);
In order to use toupper
, you need to include header file:
#include <cctype>
You also need to include header file:
#include <string>
The problem is the std::toupper
takes int
as parameter, while std::transform
will pass char
into the function, therefore, it has a problem (by courtesy of @juanchopanza).
You may try to use:
#include <functional>
std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
See example code from std::transform
Or you can implement your own toupper
that takes char
as argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With