Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c++ - How to understand passing parameter like (chosen += ch)?

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;
    }
}
question from:https://stackoverflow.com/questions/65623110/how-to-understand-passing-parameter-like-chosen-ch

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...