0

我正在使用 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== ' '))

在上述节目中。评论的人还给了我一个警告,“警告 C4805:'==':'bool' 类型和 'const char' 类型在操作中的不安全混合”

谢谢。

4

1 回答 1

5

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

于 2009-07-23T10:18:14.067 回答