Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no matching function for call to 'transform [duplicate]

Tags:

c++

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."
like image 954
user2413497 Avatar asked May 28 '13 12:05

user2413497


2 Answers

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 include cctype toupper is not guaranteed to exist in the global namespace. A cast can provide the necessary disambiguation static_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)
);
like image 77
awesoon Avatar answered Nov 08 '22 19:11

awesoon


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.

like image 3
taocp Avatar answered Nov 08 '22 18:11

taocp