A lil help pls

Guys, can you please tell me what this string iterator statement does in C++?
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ’ ';
});

where did you find it?

It modifies the string input_string and returns an iterator new_end such that the range [input_string.begin(), new_end) contains no double-spaces:

#include <iostream>
#include <algorithm>

using namespace std;

int main(int argc, char* argv[])
{
    string input_string = "hellllloo  everyoneeeee      how   are     you?    ";
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; });
    cout << string(input_string.begin(), new_end) << endl;
}

See the documentation for std::unique: std::unique - cppreference.com

Edit:

Actually, it’s technically Undefined Behaviour as the comparator used doesn’t impose an Equivalence Relation on the set of chars (the char a, for example, does not compare equal to itself).

7 Likes

In hacker rank, there was a problem related to apple and oranges, there this was used

Thanks a lot man for this much simple explanation:)

1 Like