c++ - 使用 boost::lambda_ 压缩字符串中的空格

标签 c++ stl boost-lambda

我正在使用 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'的不安全混合”

谢谢。

最佳答案

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

关于c++ - 使用 boost::lambda_ 压缩字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1170801/

相关文章:

c++ - 在C++中使循环变量成为常量

c++ - 在 C++ 中,我无法掌握指针和类

c++ - 如何使用 Boost(Lambda?)使 std::sort() 更容易?

c++ - C++ boost lambda 和 == 运算符的问题

c++ - 返回多种类型

c++ - 哪些语言生成字节码并可以在 C++ 中加载/执行

c++ - 为什么标准迭代器范围是 [begin, end) 而不是 [begin, end]?

c++ - 您是否必须在类似 STL 的类中实现多个迭代器?

c++ - 为什么在为集合执行 set_union 时需要插入函数调用?

c++ - Boost Phoenix(或 Boost Lambda)——懒惰地接受指针