代码之家  ›  专栏  ›  技术社区  ›  navigator

使用boost::lambda_u压缩字符串中的空格

  •  0
  • navigator  · 技术社区  · 16 年前

    我正在使用boost::lambda删除字符串中随后的空白,只留下一个空格。我试过这个程序。

    #include <algorithm>
    #include <iostream>
    #include <string>
    #include <boost/lambda/lambda.hpp>
    
    
    int main()
    {
        std::string s = "str     str st   st sss";
        //s.erase( std::unique(s.begin(), s.end(), (boost::lambda::_1 == ' ') && (boost::lambda::_2== ' ')), s.end()); ///< works
        s.erase( std::unique(s.begin(), s.end(), (boost::lambda::_1 == boost::lambda::_2== ' ')), s.end()); ///< does not work
        std::cout << s << std::endl;
        return 0;
    }
    

    注释行可以正常工作,但未注释行不行。

    如何

    (boost::lambda::_1 == boost::lambda::_2== ' ') 
    

    不同于

    (boost::lambda::_1 == ' ') && (boost::lambda::_2== ' '))
    

    在上面的程序中。注释的一个还警告我“warning c4805:'=':操作中类型'bool'和类型'const char'的不安全混合”

    谢谢。

    1 回复  |  直到 16 年前
        1
  •  5
  •   robson3.14    16 年前

    在C和C++中 a==b==x与(a==x)&&(b==x)非常不同, 前者解释为(a==b)==x, 比较A和B以及比较结果(对或错) 与x比较。在您的情况下,x是一个空格字符, 在使用ASCII的典型实现中,其代码等于32, 将其与转换为0或1的布尔值进行比较 总是错误的。