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

发布于 2024-07-29 02:26:41 字数 896 浏览 3 评论 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'类型的不安全混合”

谢谢。

I am using boost::lambda to remove subsequent whitespaces in a string, leaving only one space. I tried this program.

#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;
}

the commented line works fine, but the uncommented one does not.

How is

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

different from

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

in the above progam. The commented one also gives me a warning that "warning C4805: '==' : unsafe mix of type 'bool' and type 'const char' in operation"

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不乱于心 2024-08-05 02:26:41

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

In C and C++
a == b == x is very different than (a == x) && (b == x),
the former is interpreted as (a == b) == x,
which compares a with b and the result of that comparison (true or false)
is compared with x. In your case x is a space character,
and in typical implementation that uses ASCII its code is equal to 32,
comparing it with boolean value which is converted either to 0 or 1
gives always false.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文