问题
std::string decodeMorse(std::string morseCode) {
// ToDo: Accept dots, dashes and spaces, return human-readable message
std::string decoded;
for( auto p : morseCode ) {
if( p == '.' )
decoded += MORSE_CODE[ "." ];
else if( p == '-' )
decoded += MORSE_CODE[ "-" ];
}
return decoded;
}
This is a code extract from https://www.codewars.com
Can somebody explain what for( auto p : morseCode ) means?
Or perhaps re-write this piece of code in more elaborate way?
回答1:
It iterates over every element in morseCode, starting from the one begin refers to and ending with the one before end. The value of each iterated element is copied into p, whose type is the type of the dereferenced iterator.
来源:https://stackoverflow.com/questions/42657234/c-weird-for-loop-syntax