I've been doing some C++ challenges to get into coding, and I came across this when I tried to create a function that reversed a string. for some reason assigning result[i] to str[str.length() - i] doesn't work, but assigning str[str.length() - i] to holding and then holding to result[i] does. Can anyone explain this?
//this works
std::string reverse(std::string str){
std::string result;
char holding;
for(uint i = 0; i <= str.length(); i++){
holding = str[str.length() - i];
result += holding;
}
return result;
}
//this doesn't
std::string reverse(std::string str){
std::string result;
for(uint i = 0; i <= str.length(); i++){
result[i] = str[str.length() - i];
}
return result;
}