Search code examples
c++for-loopmorse-code

C++ weird for loop syntax


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?


Solution

  • 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.