我正在使用 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/