zoukankan      html  css  js  c++  java
  • [转]STL transform算法中使用toupper函数

    原文转自 http://blog.csdn.net/justin12zhu/article/details/5649236  

    今天需要实现一个把小写字母转换为大写字母的函数,由于传入的参数是STL中的string类,所以第一想法就是用transform算法来实现这功能,但是报错了。回家之后写了下面一个测试代码来看看到底错在哪里和怎么解决。

    #include <iostream>
    #include <algorithm>
    #include <cctype>
    
    using namespace std;
     
    int main(int argc, char *argv[])
    {
        string s("hello world");
        transform(s.begin(), s.end(), s.begin(), toupper);
        cout<<s<<endl;
        return 0;   
    }

    下面是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> > >, <unknown type>)'

    从上面红的部分可以看出,touppe函数被认为是未知类型的函数了。但是我另外把toupper函数独立抽出来测试的时候编译是通过的,也就是说这个函数是没问题的,那么到底问题在哪呢?

           在网上游荡一圈之后,终于找到了原因:

           标准库重载了一个touppe函数,而GCC完全由C库去提供重载,而glibc做不到这一点,所以在编译的时候g++就认为这个函数有歧义了。下面就是在标准库中toupper函数的两种形式:

    int std :: toupper ( int ); // from <cctype>
    template < class chart >
    char T std :: toupper ( char T , const locale &);  // from <locale>

        问题找出来了,但是总要有解决的方法。既然报错是因为有歧义,所以只要把歧义消除便可。

    1、通过介入包装函数

    这是最简单的办法,因为包装函数只有一个,只要在包装函数中指明要使用的函数,歧义自然就没了,以toupper为例,我们可以使用下面这样的一个包装函数:

    int toUpper( int c )
    {
           return toupper( c ) ;
    }

    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);
  • 相关阅读:
    背包问题
    基本TCP套接字编程
    P中值选址问题的整数规划求解
    Leapms + cplex解决 混合整数规划问题
    如何用整数规划求解NP完全问题
    用Leapms建摸 / 用 CPLEX 求解 旅行商问题 整数规划问题
    用线性规划建模(确定参数)关键路径法
    流水车间调度算法分析的简单+Leapms实践--混合整数规划的启发式建模
    Wolsey "强整数规划“ 建模的+Leapms实践——无产能批量问题
    Wolsey“强整数规划模型”经典案例之一单源固定费用网络流问题
  • 原文地址:https://www.cnblogs.com/CodeMIRACLE/p/5290724.html
Copyright © 2011-2022 走看看