C++ weird for loop syntax [duplicate]

╄→尐↘猪︶ㄣ 提交于 2021-02-05 12:34:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!