views:

152

answers:

1

Hi,

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.

+5  A: 

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.

robson3.14
silly me. You're right. Thanks :)
navigator