1

I am a beginner of C++. I am trying to fix a permutation function. I know the bug here is chosen += ch, it should be chosen + ch, but I do not understand how chosen += ch can be passed as a parameter here and what it means.

HashSet<string> permutationsRec(string str, string chosen) {
    if (str == "") {
        return { chosen };
    }
    else {
        HashSet<string> result;
        for (int i = 0; i < str.size(); i++) {
            char ch = str[i];
            string remaining = str.substr(0, i) + str.substr(i + 1);

            HashSet<string> thisOption = permutationsRec(remaining, chosen += ch);
            result += thisOption;
        }
        return result;
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jack
  • 11
  • 1
  • 2
    Both `chosen += ch` and `chosen + ch` pass the same string value into the recursive call. Difference is that `+=` also modifies `chosen` in the caller, while `+` does not. – dxiv Jan 08 '21 at 03:40

3 Answers3

0

In C (and C++), an assignment is not only a statement but also an expression that can be used within another statement. Both = and += will modify their left hand operand, but they will also evaluate to another value that can be part of a larger expression. Typically they will be the same value as the result of the = or += operation, though with C++ overloaded operators it could be just about anything.

B. Morris
  • 630
  • 3
  • 15
0

In C++, we have a concept: expression (https://en.cppreference.com/w/cpp/language/expressions).

An expression can be evaluated, meaning that we can get a value from an expression, and an expression may have some side-effects (What exactly is a 'side-effect' in C++?).

For example,

int a = 1;
int b = 2;
int c = 0;
c = a + b;

Here, c = a + b is an assignment expression. When we evaluate an assignment expression, its value is the left operand of =, so the value of c = a + b is obviously the value of c, which equals to 3. And its side-effect is that the value of the variable c is changed.

In your code, chosen += ch is obviously an expression (chosen = chosen + ch), so it can be evaluated and it has an side effect (the value of chosen is changed).

So why can chosen += ch be passed to a function as a parameter? The answer is because it can be evaluated.

There are many different kinds of expressions, some of them may be counter-intuitive or weird, but this is how C++ is designed. For example, we have comma operator expression, so we can code c = (1, 2);: https://www.geeksforgeeks.org/comna-in-c-and-c/

One more thing, expression and statement are different: https://en.cppreference.com/w/cpp/language/statements

Yves
  • 11,597
  • 17
  • 83
  • 180
-1

http://www.cplusplus.com/reference/string/string/operator+=/

You can add a char to the end of a string using the += operator.

Since permutationsRec takes two strings as arguments and chosen += ch returns a string, you can use it as an argument in the function call.