transform算法中使用toupper函数
今天需要实现一个把小写字母转换为大写字母的函数,由于传入的参数是SL中的string类,所以第一想法就是用transform算法来实现这功能,但是报错了。回家之后写了下面一个测试代码来看看到底错在哪里和怎么解决。
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
}
下面是g++的报错信息:
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> >>, <unknowntype>)'
从上面红的部分可以看出,touppe函数被认为是未知类型的函数了。但是我另外把toupper函数独立抽出来测试的时候编译是通过的,也就是说这个函数是没问题的,那么到底问题在哪呢?
int std :: toupper ( int ); // from<cctype>
template < class chart >
charT std :: toupper ( charT , const locale&);
1、通过介入包装函数
这是最简单的办法,因为包装函数只有一个,只要在包装函数中指明要使用的函数,歧义自然就没了,以toupper为例,我们可以使用下面这样的一个包装函数:
{
}
2、强制转化:将toupper转换为一个返回值为int,参数只有一个int的函数指针:
std::transform(s.begin(), s.end(), s.begin(), (int(*)(int))toupper);
3、GCC中将toupper实现为一个宏而不是函数,而在全局命名空间中有实现的函数(而不是宏),所以我们明确命名空间,这并不是总奏效,但是在我的g++环境中没有问题:
transform(s.begin(), s.end(), s.begin(), ::toupper);
联系客服