C++ STL string 大小写转换时的 no matching function for call to ‘transform 错误

C++ STL字符串大小写转换
本文介绍使用C++ STL进行字符串大小写转换时遇到的编译错误,并提供了解决方案。通过明确指定使用C标准库中的toupper和tolower函数,可以避免与STL模板函数的冲突。

出处:http://blog.youkuaiyun.com/yasi_xi/article/details/9053279

C++ STL string 大小写转换时的 no matching function for call to ‘transform 错误

这里介绍了 C++ STL string 大小写转换的代码,但是要注意,可能有些机器用下面的代码编译不过

  1. #include <cctype> // toupper, tolower  
  2. #include <iostream>  
  3. #include <string>  
  4. #include <algorithm>    // transform  
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.    string str = "abcdADcdeFDde!@234";  
  10.    transform(str.begin(), str.end(), str.begin(), toupper);  
  11.    cout << str << endl;  
  12.    transform(str.begin(), str.end(), str.begin(), tolower);  
  13.    cout << str << endl;  
  14.    return 0;  
  15. }  

可能的错误提示如下:

  1. 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> > >, <unknown type>)’  

这里 说明了原因:

The problem is that the version of std::tolower inherited from the C standard library is a non-template function, but there are other versions of std::tolower that are function templates, and it is possible for them to be included depending on the standard library implementation. You actually want to use the non-template function, but there is ambiguity when just tolower is provided as the predicate.

翻译过来就是说,既有C版本的toupper/tolower函数,又有STL模板函数toupper/tolower,二者存在冲突。


解决办法:

在toupper/tolower前面加::,强制指定是C版本的(这时也不要include <cctype>了):

  1. #include <iostream>  
  2. #include <string>  
  3. #include <algorithm>    // transform  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.    string str = "abcdADcdeFDde!@234";  
  9.    transform(str.begin(), str.end(), str.begin(), ::toupper);  
  10.    cout << str << endl;  
  11.    transform(str.begin(), str.end(), str.begin(), ::tolower);  
  12.    cout << str << endl;  
  13.    return 0;  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值